diff --git a/csv/ipo_settings.json b/csv/ipo_settings.json new file mode 100644 index 0000000..c16386b --- /dev/null +++ b/csv/ipo_settings.json @@ -0,0 +1 @@ +{"feature": "IPO", "speed": "medium", "speed2": "medium", "animation": "down", "title": true, "symbols": ["No Data"]} \ No newline at end of file diff --git a/csv/last_updates.json b/csv/last_updates.json index 061daa6..02368cb 100644 --- a/csv/last_updates.json +++ b/csv/last_updates.json @@ -1 +1 @@ -{"stocks": {"time": "14/06/2022 06:42:06", "force": false}, "crypto": {"time": "14/06/2022 06:58:18", "force": false}, "news": {"time": "14/06/2022 05:29:08", "force": false}, "weather": {"time": "14/06/2022 05:29:08", "force": false}, "forex": {"time": "14/06/2022 05:29:14", "force": false}, "sports_l": {"time": "14/06/2022 04:42:37", "force": false}, "sports_p": {"time": "14/06/2022 06:27:34", "force": false}, "sports_u": {"time": "14/06/2022 06:28:34", "force": false}, "sports_t": {"time": "14/06/2022 06:26:23", "force": false}, "commodities": {"time": "14/06/2022 06:51:07", "force": false}, "indices": {"time": "05/10/2022 04:06:10", "force": false}, "movies": {"time": "05/10/2022 02:31:40", "force": false}} +{"scheduler":{"force": false}, "stocks": {"time": "14/06/2022 06:42:06", "force": false}, "crypto": {"time": "14/06/2022 06:58:18", "force": false}, "news": {"time": "14/06/2022 05:29:08", "force": false}, "weather": {"time": "14/06/2022 05:29:08", "force": false}, "forex": {"time": "14/06/2022 05:29:14", "force": false}, "sports_l": {"time": "14/06/2022 04:42:37", "force": false}, "sports_p": {"time": "14/06/2022 06:27:34", "force": false}, "sports_u": {"time": "14/06/2022 06:28:34", "force": false}, "sports_t": {"time": "14/06/2022 06:26:23", "force": false}, "commodities": {"time": "14/06/2022 06:51:07", "force": false}, "indices": {"time": "05/10/2022 04:06:10", "force": false}, "movies": {"time": "05/10/2022 02:31:40", "force": false}, "ipo": {"time": "05/10/2022 02:31:40", "force": false}, "prepost": {"time": "05/10/2022 02:31:40", "force": false}} diff --git a/database_caller.py b/database_caller.py index 89135cc..39178e2 100755 --- a/database_caller.py +++ b/database_caller.py @@ -28,6 +28,7 @@ try: last_updates = json.load(f) f.close() last_updates['stocks']['force'] = True + last_updates['prepost']['force'] = True last_updates['sports_l']['force'] = True f = open('csv/last_updates.json', 'w') json.dump(last_updates, f) @@ -35,6 +36,31 @@ try: except: pass +try: + f = open('csv/scheduler.json', 'r') + schedules = json.load(f) + f.close() + + shutdown_schedule_hour = schedules['shutdown']['hour'] + shutdown_schedule_minute = schedules['shutdown']['minute'] + + reboot_schedule_hour = schedules['reboot']['hour'] + reboot_schedule_minute = schedules['reboot']['minute'] + + timezone = schedules['timezone'] + shutdown_enabled = schedules['shutdown']['enabled'] + reboot_enabled = schedules['reboot']['enabled'] +except: + shutdown_schedule_hour = "00" + shutdown_schedule_minute = "00" + + reboot_schedule_hour = "00" + reboot_schedule_minute = "00" + + timezone = "GMT" + shutdown_enabled = False + reboot_enabled = False + def getInput(Block=False): if Block or select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): @@ -112,6 +138,71 @@ def updateStocks(api_key, logf): #logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) #logf.close() + +def updateStocksPrePost(api_key, logf): + + try: + + f = open('csv/stocks_settings.json', 'r') + all_stocks_settings = json.load(f) + f.close() + stock_info = all_stocks_settings['symbols'] + symbols = list(stock_info.keys()) + + #KEEP THIS JUST IN CASE V7 GOES DOWN prepost_url = 'https://query2.finance.yahoo.com/v6/finance/quote?symbols=' + prepost_url = 'https://query2.finance.yahoo.com/v7/finance/quote?symbols=' + for symbol in symbols: + prepost_url += symbol + ',' + + prepost_url += '&fields=regularMarketPreviousClose,regularMarketPrice,preMarketPrice,preMarketChangePercent,regularMarketChangePercent,regularMarketChange,preMarketChange,postMarketPrice,postMarketChange,postMarketChangePercent®ion=US&lang=en-US' + + headers = { + 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' + } + prepost = requests.get(prepost_url, headers=headers) + + if 'Unauthorized' in str(prepost.json()): + prepost = requests.get(prepost_url.replace('v7','v6'), headers=headers) + + prepost_data = prepost.json()['quoteResponse']['result'] + time_now = datetime.now(pytz.timezone('America/New_York')).strftime("%H:%M EST") + + if len(prepost_data) > 0: + for symbol in symbols: + for stock in prepost_data: + if stock['symbol'] == symbol: + stock_info[stock['symbol']] = {"time_now":time_now} + try: + stock_info[stock['symbol']]['Pre-market'] = {'preprice': '%.2f' % stock['preMarketPrice'], + 'prechange': '%.2f' % stock['preMarketChange'], + 'prepercent': '%.2f' % stock['preMarketChangePercent']} + except: + try: + stock_info[stock['symbol']]['Pre-market'] = {'preprice': '%.2f' % stock['postMarketPrice'], + 'prechange': '%.2f' % 0, + 'prepercent': '%.2f' % 0} + except: + stock_info[stock['symbol']]['Pre-market'] = {'preprice': '%.2f' % stock['regularMarketPrice'], + 'prechange': '%.2f' % 0, + 'prepercent': '%.2f' % 0} + try: + stock_info[stock['symbol']]['Post-market'] = {'postprice': '%.2f' % stock['postMarketPrice'], + 'postchange': '%.2f' % stock['postMarketChange'], + 'postpercent': '%.2f' % stock['postMarketChangePercent']} + except: + stock_info[stock['symbol']]['Post-market'] = {'postprice': '%.2f' % stock['regularMarketPrice'], + 'postchange': '%.2f' % 0, + 'postpercent': '%.2f' % 0} + + all_stocks_settings['symbols'] = stock_info + + with open('csv/prepost_settings.json', 'w+') as f: + json.dump(all_stocks_settings['symbols'], f) + + except: + pass + + def updateCommodities(api_key, logf): try: @@ -290,7 +381,61 @@ def updateMovies(api_key, logf): f = open('csv/movie_settings.json', 'w+') json.dump(all_settings, f) f.close() - + + +def updateIpo(api_key, logf): + + day = datetime.now(pytz.utc).strftime("%Y-%m-%d") + dt = datetime.strptime(day, "%Y-%m-%d") + + start = (dt - timedelta(days=dt.weekday())) + start_date = start.strftime("%Y-%m-%d") + + end = start + timedelta(days=21) + end_date = end.strftime("%Y-%m-%d") + + ipo_url = 'https://finnhub.io/api/v1/calendar/ipo?from='+start_date+'&to='+end_date+'&token='+api_key + + f = open('csv/ipo_settings.json', 'r') + ipo_settings = json.load(f) + f.close() + + data = requests.get(ipo_url) + all_ipo = data.json() + + ipo_list = [] + + try: + if len(all_ipo['ipoCalendar']) > 0: + for ipo in all_ipo['ipoCalendar']: + try: + shares = human_format(ipo['numberOfShares']) + except: + shares = 'N/A' + try: + sharesvalue = human_format(ipo['totalSharesValue']) + except: + sharesvalue = 'N/A' + + ipo_list.append({ + 'date':ipo['date'], + 'name':ipo['name'], + 'shares':shares, + 'price':ipo['price'], + 'status':ipo['status'], + 'symbol':ipo['symbol'], + 'sharesvalue':sharesvalue + }) + else: + ipo_list = ['No Data'] + except: + ipo_list = ['No Data'] + + ipo_settings['symbols'] = ipo_list + f = open('csv/ipo_settings.json', 'w+') + json.dump(ipo_settings, f) + f.close() + def updateIndices(api_key, logf): @@ -462,24 +607,16 @@ def updateForex(api_key, logf): def updateNews(api_key, logf): - #'https://bm7p954xoh.execute-api.us-east-2.amazonaws.com/default/ScriptsAPI/news?category=technology' - #'https://bm7p954xoh.execute-api.us-east-2.amazonaws.com/default/ScriptsAPI/news?country=GB' - #'https://bm7p954xoh.execute-api.us-east-2.amazonaws.com/default/ScriptsAPI/news?lang=en' - - try: f = open('csv/news_settings.json', 'r') all_settings = json.load(f) f.close() - - - - + if all_settings['use_country']: if all_settings['country'] == 'Worldwide': url = 'https://bm7p954xoh.execute-api.us-east-2.amazonaws.com/default/ScriptsAPI/news_worldwide?' else: - c_dict = {'United States':'US', 'Australia':'AU', 'Canada': 'CA', 'Great Britain':'GB', 'New Zealand':'NZ', 'Ireland':'IE', 'Singapore':'SG', 'South Africa': 'ZA'} + c_dict = {'United States':'US', 'Australia':'AU', 'Canada': 'CA', 'Great Britain':'GB', 'New Zealand':'NZ', 'Ireland':'IE', 'Singapore':'SG', 'South Africa': 'ZA', 'Germany': 'DE', 'Hong Kong': 'HK', 'Japan': 'JP', 'South Korea': 'KR', 'China': 'CN', 'France': 'FR', 'India': 'IN', 'Italy': 'IT', 'Switzerland': 'CH', 'Netherlands': 'NL', 'Spain': 'ES', 'Brazil': 'BR', 'Portugal': 'PT'} cc = c_dict[all_settings['country']] url = 'https://bm7p954xoh.execute-api.us-east-2.amazonaws.com/default/ScriptsAPI/news?country={}'.format(cc) elif all_settings['use_category']: @@ -493,9 +630,7 @@ def updateNews(api_key, logf): max_headlines = int(all_settings['num_headlines']) #load user settings headlines = data[:max_headlines] - headline_sources = [headline['source'] for headline in headlines] - - + headline_sources = [headline['source'] for headline in headlines] headline_titles = [headline['title'] for headline in headlines] headline_times = [headline['publishedAt'] for headline in headlines] @@ -801,72 +936,217 @@ def updateLeagueEvents(api_key, time, logf): for league in all_data.keys(): ten_or_fifteen = slice(None) events = [] - if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'): + if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'F1') or (league == 'NASCAR'): ten_or_fifteen = slice(3) else: ten_or_fifteen = slice(None) - for d in all_data[league][ten_or_fifteen]: - event = {} - event['date'] = d['dateEvent'] - - if time == 'live': - event['progess'] = d['strProgress'] - event['status'] = d['strStatus'] - else: - if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'): - event['date'] = d['dateEvent'] - event['event'] = d['strEvent'].replace("\u2019","'") - event['venue'] = d['strVenue'].replace("\u2019","'") - event['city'] = d['strCity'].replace("\u2019","'") - event['country'] = d['strCountry'] - event['season'] = d['strSeason'] - else: - event['round'] = d['intRound'] - event['time'] = d['strTime'] - event['home_team'] = d['strHomeTeam'] - event['away_team'] = d['strAwayTeam'] - - if time != 'upcoming': - if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'): - event['golf_standings'] = d['strResult'] - - rank = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9', 'n10', 'T1', 'T2', 'T3', 'T4', 'T5', - 'T6', 'T7', 'T8', 'T9', 'T10'] - - def convert(string): - string = repr(string).replace('/', '') - li = list(string.split('\\')) - return li - - str3 = convert(event['golf_standings']) - - players = [] - - - for each in str3: - each = each.replace('nT', 'T', 1) - if each[:2] in rank: - try: - first_space = each.find(' ', 1) - second_space = each.find(' ', 4) - first_name = each[first_space:second_space].lstrip() - initial = first_name[0] + '.' - each = each.replace(first_name,initial) - except: - pass - interator = each.find('-') - if interator < 0: - interator = 0 - interator2 = each[interator:interator + 3] - result = each.split(interator2, 1)[0] + interator2 - players.append(result.rstrip()) - - event['golf_standings'] = players - else: - event['away_score'] = d['intAwayScore'] - event['home_score'] = d['intHomeScore'] + if league == 'UFC': + event = all_data['UFC'][0] events.append(event) + if time == 'upcoming': + try: + logo_files = [] + for each in all_data['UFC'][0]['fights']: + try: + if each['fighter1pic'].split('/')[-1].split('&')[0] not in os.listdir('logos/ufc/'): + urllib.request.urlretrieve(each['fighter1pic'],'logos/ufc/' + each['fighter1pic'].split('/')[-1].split('&')[0]) + except: + pass + try: + if each['fighter2pic'].split('/')[-1].split('&')[0] not in os.listdir('logos/ufc/'): + urllib.request.urlretrieve(each['fighter2pic'],'logos/ufc/' + each['fighter2pic'].split('/')[-1].split('&')[0]) + except: + pass + try: + logo_files.append(each['fighter2pic'].split('/')[-1].split('&')[0]) + except: + pass + try: + logo_files.append(each['fighter1pic'].split('/')[-1].split('&')[0]) + except: + pass + #country flags + try: + if each['fighter1country'].split('/')[-1].split('&')[0] not in os.listdir('logos/ufc_countries/'): + urllib.request.urlretrieve(each['fighter1country'], 'logos/ufc_countries/' + each['fighter1country'].split('/')[-1].split('&')[0]) + except: + pass + try: + if each['fighter2country'].split('/')[-1].split('&')[0] not in os.listdir('logos/ufc_countries/'): + urllib.request.urlretrieve(each['fighter2country'], 'logos/ufc_countries/' + each['fighter2country'].split('/')[-1].split('&')[0]) + except: + pass + + for file in os.listdir('logos/ufc/'): + if file not in logo_files: + os.remove('logos/ufc/'+ file) + except: + pass + elif time == 'past': + try: + logo_files = [] + for each in all_data['UFC'][0]['fights']: + try: + if each['fighter1pic'].split('/')[-1].split('&')[0] not in os.listdir('logos/ufc_past/'): + urllib.request.urlretrieve(each['fighter1pic'],'logos/ufc_past/' + each['fighter1pic'].split('/')[-1].split('&')[0]) + except: + pass + try: + if each['fighter2pic'].split('/')[-1].split('&')[0] not in os.listdir('logos/ufc_past/'): + urllib.request.urlretrieve(each['fighter2pic'],'logos/ufc_past/' + each['fighter2pic'].split('/')[-1].split('&')[0]) + except: + pass + try: + logo_files.append(each['fighter2pic'].split('/')[-1].split('&')[0]) + except: + pass + try: + logo_files.append(each['fighter1pic'].split('/')[-1].split('&')[0]) + except: + pass + #country flags + try: + if each['fighter1country'].split('/')[-1].split('&')[0] not in os.listdir('logos/ufc_countries/'): + urllib.request.urlretrieve(each['fighter1country'], 'logos/ufc_countries/' + each['fighter1country'].split('/')[-1].split('&')[0]) + except: + pass + try: + if each['fighter2country'].split('/')[-1].split('&')[0] not in os.listdir('logos/ufc_countries/'): + urllib.request.urlretrieve(each['fighter2country'], 'logos/ufc_countries/' + each['fighter2country'].split('/')[-1].split('&')[0]) + except: + pass + + for file in os.listdir('logos/ufc_past/'): + if file not in logo_files: + os.remove('logos/ufc_past/'+ file) + except: + pass + else: + for d in all_data[league][ten_or_fifteen]: + event = {} + event['date'] = d['dateEvent'] + try: + event['date2'] = d['dateEvent2'] + except: + pass + + if time == 'live': + event['progess'] = d['strProgress'] + event['status'] = d['strStatus'] + else: + if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'F1') or (league == 'NASCAR'): + event['date'] = d['dateEvent'] + try: + event['date2'] = d['dateEvent2'] + except: + pass + event['event'] = d['strEvent'].replace("\u2019","'") + event['venue'] = d['strVenue'].replace("\u2019","'") + event['city'] = d['strCity'].replace("\u2019","'") + event['country'] = d['strCountry'] + event['season'] = d['strSeason'] + else: + event['round'] = d['intRound'] + event['time'] = d['strTime'] + event['home_team'] = d['strHomeTeam'] + event['away_team'] = d['strAwayTeam'] + + if time != 'upcoming': + if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'): + event['golf_standings'] = d['strResult'] + + rank = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9', 'n10', 'T1', 'T2', 'T3', 'T4', 'T5', + 'T6', 'T7', 'T8', 'T9', 'T10'] + + def convert(string): + string = repr(string).replace('/', '') + li = list(string.split('\\')) + return li + + str3 = convert(event['golf_standings']) + + players = [] + + + for each in str3: + each = each.replace('nT', 'T', 1) + if each[:2] in rank: + try: + first_space = each.find(' ', 1) + second_space = each.find(' ', 4) + first_name = each[first_space:second_space].lstrip() + initial = first_name[0] + '.' + each = each.replace(first_name,initial) + except: + pass + interator = each.find('-') + if interator < 0: + interator = 0 + interator2 = each[interator:interator + 3] + result = each.split(interator2, 1)[0] + interator2 + players.append(result.rstrip()) + + event['golf_standings'] = players + + + elif (league == 'LIV'): + event['golf_standings'] = d['strResult'] + + rank = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9', 'n10', 'T1', 'T2', 'T3', 'T4', 'T5', + 'T6', 'T7', 'T8', 'T9', 'T10'] + + def convert(string): + string = repr(string).replace('/', '') + li = list(string.split('\\')) + return li + + try: + str3 = convert(event['golf_standings'].split('--------------------------------------')[0]) + strTeams = convert(event['golf_standings'].split('--------------------------------------')[1]) + except: + pass + + players = [] + teams = [] + + try: + for each in str3: + each = each.replace('nT', 'T', 1) + if each[:2] in rank: + try: + first_space = each.find(' ', 1) + second_space = each.find(' ', 4) + first_name = each[first_space:second_space].lstrip() + initial = first_name[0] + '.' + each = each.replace(first_name,initial) + except: + pass + interator = each.find('-') + if interator < 0: + interator = 0 + interator2 = each[interator:interator + 3] + result = each.split(interator2, 1)[0] + interator2 + players.append(result.rstrip()) + + for each in strTeams: + each = each.replace('nT', 'T', 1) + if each[:2] in rank: + each = each.split('GC') + score = each[1].rfind(' ') + score2 = each[1][score:score+4] + each2 = each[0] + score2 + teams.append(each2) + except: + pass + + event['golf_standings'] = [players] + [teams] + + else: + event['away_score'] = d['intAwayScore'] + event['home_score'] = d['intHomeScore'] + + events.append(event) leagues_info[league.upper()] = events all_settings['leagues'] = leagues_info @@ -875,15 +1155,7 @@ def updateLeagueEvents(api_key, time, logf): f.close() except: pass - #logf = open('log.txt', "a") - #exc_type, exc_obj, exc_tb = sys.exc_info() - #fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] - #logf.write(str(e)) - #logf.write('. file: ' + fname) - #logf.write('. line: ' + str(exc_tb.tb_lineno)) - #logf.write('. type: ' + str(exc_type)) - #logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) - #logf.close() + def updateSports(api_key, logf): @@ -967,7 +1239,7 @@ if __name__ == '__main__': - update_frequencies = {'stocks':2, 'crypto':5, 'forex':60, 'news':120, 'weather': 120, 'sports': 1440, 'commodities': 15, 'indices': 15, 'movies': 1440} #minutes + update_frequencies = {'stocks':2, 'crypto':7, 'forex':60, 'news':120, 'weather': 120, 'sports': 1440, 'commodities': 15, 'indices': 15, 'movies': 1440, 'ipo': 1440, 'prepost': 15} #minutes NY_zone = pytz.timezone('America/New_York') CET_zone = pytz.timezone('EST') @@ -1009,6 +1281,10 @@ if __name__ == '__main__': except Exception as e: movie_key = False + try: + ipo_key = open('ipo_api_key.txt').readlines()[0] + except Exception as e: + ipo_key = False t = time.time() update_processes = [] @@ -1037,15 +1313,54 @@ if __name__ == '__main__': f.close() except: - last_updates = {"stocks": {"time": "06/03/2022 04:12:09", "force": True}, "crypto": {"time": "06/03/2022 04:10:39", "force": True}, + last_updates = {"scheduler":{"force": False}, "stocks": {"time": "06/03/2022 04:12:09", "force": True}, "crypto": {"time": "06/03/2022 04:10:39", "force": True}, "news": {"time": "06/03/2022 04:07:09", "force": True}, "weather": {"time": "06/03/2022 04:08:20", "force": True}, "forex": {"time": "06/03/2022 03:54:02", "force": True}, "sports_l": {"time": "06/03/2022 04:10:09", "force": True}, "sports_p": {"time": "06/03/2022 04:10:09", "force": True}, - "sports_u": {"time": "06/03/2022 04:10:09", "force": True},"sports_t": {"time": "06/03/2022 04:10:09", "force": True}, "commodities": {"time": "06/03/2022 04:10:09", "force": True}, "indices": {"time": "06/03/2022 04:10:09", "force": True}, "movies": {"time": "06/03/2022 04:10:09", "force": True}} + "sports_u": {"time": "06/03/2022 04:10:09", "force": True},"sports_t": {"time": "06/03/2022 04:10:09", "force": True}, "commodities": {"time": "06/03/2022 04:10:09", "force": True}, "indices": {"time": "06/03/2022 04:10:09", "force": True}, "movies": {"time": "06/03/2022 04:10:09", "force": True}, "ipo": {"time": "06/03/2022 04:10:09", "force": True}, "prepost": {"time": "06/03/2022 04:10:09", "force": True}} - - - + try: + if last_updates['scheduler']['force']: + try: + f = open('csv/scheduler.json','r') + schedules = json.load(f) + f.close() + shutdown_schedule_hour = schedules['shutdown']['hour'] + shutdown_schedule_minute = schedules['shutdown']['minute'] + + reboot_schedule_hour = schedules['reboot']['hour'] + reboot_schedule_minute = schedules['reboot']['minute'] + + timezone = schedules['timezone'] + shutdown_enabled = schedules['shutdown']['enabled'] + reboot_enabled = schedules['reboot']['enabled'] + except: + shutdown_schedule_hour = "00" + shutdown_schedule_minute = "00" + + reboot_schedule_hour = "00" + reboot_schedule_minute = "00" + + timezone = "GMT" + shutdown_enabled = False + reboot_enabled = False + last_updates['scheduler']['force'] = False + except: + pass +#SHUTDOWN + try: + if datetime.now(pytz.timezone(timezone)).strftime("%H:%M") == shutdown_schedule_hour+':'+shutdown_schedule_minute and shutdown_enabled: + os.system('sudo shutdown now') + except: + pass +#REBOOT + try: + if datetime.now(pytz.timezone(timezone)).strftime("%H:%M") == reboot_schedule_hour+':'+reboot_schedule_minute and reboot_enabled: + os.system('sudo reboot') + except: + pass + + NY_time = datetime.now(NY_zone).replace(tzinfo=None) #msg = getInput() @@ -1072,6 +1387,33 @@ if __name__ == '__main__': update_process = Process(target = updateStocks, args = (api_key,logf)) update_process.start() update_processes.append(update_process) + + NY_time1 = datetime.now(NY_zone).replace(tzinfo=None) + NY_time2 = datetime.now(NY_zone).replace(tzinfo=None) + #prepost + + preopen = NY_time1.replace(hour=4, minute=0, second=0, microsecond=0).replace(tzinfo=None) + preclose = NY_time1.replace(hour=9, minute=30, second=0, microsecond=0).replace(tzinfo=None) + + postopen = NY_time2.replace(hour=16, minute=0, second=0, microsecond=0).replace(tzinfo=None) + postclose = NY_time2.replace(hour=20, minute=20, second=0, microsecond=0).replace(tzinfo=None) + + prepost_frequency = update_frequencies['prepost'] + prepost_time = datetime.strptime(last_updates['prepost']['time'], "%d/%m/%Y %H:%M:%S") + + pre_open = preopen < NY_time1 < preclose and NY_time1.weekday() <= 4 + post_open = postopen < NY_time2 < postclose and NY_time2.weekday() <= 4 + + diff1 = (NY_time1 - prepost_time).total_seconds()/60 #minutes + diff2 = (NY_time2 - prepost_time).total_seconds()/60 #minutes + + if (last_updates['prepost']['force']) or (diff1 >= update_frequencies['prepost'] and pre_open) or (diff2 >= update_frequencies['prepost'] and post_open): + prepost_time = NY_time1.strftime("%d/%m/%Y %H:%M:%S") + last_updates['prepost']['time'] = prepost_time + last_updates['prepost']['force'] = False + update_process = Process(target = updateStocksPrePost, args = (api_key,logf)) + update_process.start() + update_processes.append(update_process) # crypto crypto_time = datetime.strptime(last_updates['crypto']['time'], "%d/%m/%Y %H:%M:%S") @@ -1144,6 +1486,24 @@ if __name__ == '__main__': update_process.start() update_processes.append(update_process) + + # ipos + ipo_time = datetime.strptime(last_updates['ipo']['time'], "%d/%m/%Y %H:%M:%S") + + + NY_time = datetime.now(NY_zone).replace(tzinfo=None) + diff = (NY_time - ipo_time).total_seconds()/60 #minutes + + + if last_updates['ipo']['force'] or diff >= update_frequencies['ipo']: + ipo_time = NY_time.strftime("%d/%m/%Y %H:%M:%S") + last_updates['ipo']['time'] = ipo_time + last_updates['ipo']['force'] = False + update_process = Process(target = updateIpo, args = (ipo_key,logf)) + update_process.start() + update_processes.append(update_process) + + # weather weather_time = datetime.strptime(last_updates['weather']['time'], "%d/%m/%Y %H:%M:%S") diff --git a/feature_titles/ipo.png b/feature_titles/ipo.png new file mode 100644 index 0000000..ec17744 Binary files /dev/null and b/feature_titles/ipo.png differ diff --git a/feature_titles/small_feature_titles/ipo.png b/feature_titles/small_feature_titles/ipo.png new file mode 100644 index 0000000..9455780 Binary files /dev/null and b/feature_titles/small_feature_titles/ipo.png differ diff --git a/logos/commodities/CATTLE(lb).png b/logos/commodities/CATTLE(lb).png new file mode 100644 index 0000000..1e7efd2 Binary files /dev/null and b/logos/commodities/CATTLE(lb).png differ diff --git a/logos/commodities/HOG(lb).png b/logos/commodities/HOG(lb).png new file mode 100644 index 0000000..a6bd9b4 Binary files /dev/null and b/logos/commodities/HOG(lb).png differ diff --git a/logos/down-tiny.png b/logos/down-tiny.png new file mode 100644 index 0000000..4097b9d Binary files /dev/null and b/logos/down-tiny.png differ diff --git a/logos/news_logos/69news-wfmz-tv.png b/logos/news_logos/69news-wfmz-tv.png new file mode 100644 index 0000000..603da7c Binary files /dev/null and b/logos/news_logos/69news-wfmz-tv.png differ diff --git a/logos/news_logos/8-days.png b/logos/news_logos/8-days.png new file mode 100644 index 0000000..c81395c Binary files /dev/null and b/logos/news_logos/8-days.png differ diff --git a/logos/news_logos/brookings-institution.png b/logos/news_logos/brookings-institution.png new file mode 100644 index 0000000..a4a2df6 Binary files /dev/null and b/logos/news_logos/brookings-institution.png differ diff --git a/logos/news_logos/c-span-.png b/logos/news_logos/c-span-.png new file mode 100644 index 0000000..c078d4c Binary files /dev/null and b/logos/news_logos/c-span-.png differ diff --git a/logos/news_logos/carnegie-europe.png b/logos/news_logos/carnegie-europe.png new file mode 100644 index 0000000..60a0d1f Binary files /dev/null and b/logos/news_logos/carnegie-europe.png differ diff --git a/logos/news_logos/cheddar.png b/logos/news_logos/cheddar.png new file mode 100644 index 0000000..e11b1d9 Binary files /dev/null and b/logos/news_logos/cheddar.png differ diff --git a/logos/news_logos/coindesk.png b/logos/news_logos/coindesk.png new file mode 100644 index 0000000..cefd317 Binary files /dev/null and b/logos/news_logos/coindesk.png differ diff --git a/logos/news_logos/dentons.png b/logos/news_logos/dentons.png new file mode 100644 index 0000000..61112aa Binary files /dev/null and b/logos/news_logos/dentons.png differ diff --git a/logos/news_logos/dutchnews.nl.png b/logos/news_logos/dutchnews.nl.png new file mode 100644 index 0000000..6093ca5 Binary files /dev/null and b/logos/news_logos/dutchnews.nl.png differ diff --git a/logos/news_logos/euractiv.png b/logos/news_logos/euractiv.png new file mode 100644 index 0000000..fb542ba Binary files /dev/null and b/logos/news_logos/euractiv.png differ diff --git a/logos/news_logos/eurasian-times.png b/logos/news_logos/eurasian-times.png new file mode 100644 index 0000000..60236dd Binary files /dev/null and b/logos/news_logos/eurasian-times.png differ diff --git a/logos/news_logos/european-commission.png b/logos/news_logos/european-commission.png new file mode 100644 index 0000000..3a854be Binary files /dev/null and b/logos/news_logos/european-commission.png differ diff --git a/logos/news_logos/foreign-policy.png b/logos/news_logos/foreign-policy.png new file mode 100644 index 0000000..59c7e59 Binary files /dev/null and b/logos/news_logos/foreign-policy.png differ diff --git a/logos/news_logos/gulf-news.png b/logos/news_logos/gulf-news.png new file mode 100644 index 0000000..2551aa8 Binary files /dev/null and b/logos/news_logos/gulf-news.png differ diff --git a/logos/news_logos/japan-today.png b/logos/news_logos/japan-today.png new file mode 100644 index 0000000..bb82f79 Binary files /dev/null and b/logos/news_logos/japan-today.png differ diff --git a/logos/news_logos/kcrw.png b/logos/news_logos/kcrw.png new file mode 100644 index 0000000..992b0b2 Binary files /dev/null and b/logos/news_logos/kcrw.png differ diff --git a/logos/news_logos/latestly.png b/logos/news_logos/latestly.png new file mode 100644 index 0000000..37a998d Binary files /dev/null and b/logos/news_logos/latestly.png differ diff --git a/logos/news_logos/markets-insider.png b/logos/news_logos/markets-insider.png new file mode 100644 index 0000000..8c48517 Binary files /dev/null and b/logos/news_logos/markets-insider.png differ diff --git a/logos/news_logos/marketscreener.com.png b/logos/news_logos/marketscreener.com.png new file mode 100644 index 0000000..5f72a6e Binary files /dev/null and b/logos/news_logos/marketscreener.com.png differ diff --git a/logos/news_logos/mingtiandi.png b/logos/news_logos/mingtiandi.png new file mode 100644 index 0000000..0c8494e Binary files /dev/null and b/logos/news_logos/mingtiandi.png differ diff --git a/logos/news_logos/mint.png b/logos/news_logos/mint.png new file mode 100644 index 0000000..89aa46f Binary files /dev/null and b/logos/news_logos/mint.png differ diff --git a/logos/news_logos/new-scientist.png b/logos/news_logos/new-scientist.png index b2f268b..f8b31ea 100755 Binary files a/logos/news_logos/new-scientist.png and b/logos/news_logos/new-scientist.png differ diff --git a/logos/news_logos/news-12-bronx.png b/logos/news_logos/news-12-bronx.png new file mode 100644 index 0000000..b04b4e3 Binary files /dev/null and b/logos/news_logos/news-12-bronx.png differ diff --git a/logos/news_logos/nikkei-asia.png b/logos/news_logos/nikkei-asia.png new file mode 100644 index 0000000..9e30d5f Binary files /dev/null and b/logos/news_logos/nikkei-asia.png differ diff --git a/logos/news_logos/oecd.png b/logos/news_logos/oecd.png new file mode 100644 index 0000000..e235d89 Binary files /dev/null and b/logos/news_logos/oecd.png differ diff --git a/logos/news_logos/pbs-newshour.png b/logos/news_logos/pbs-newshour.png new file mode 100644 index 0000000..00039a4 Binary files /dev/null and b/logos/news_logos/pbs-newshour.png differ diff --git a/logos/news_logos/pew-research-center.png b/logos/news_logos/pew-research-center.png new file mode 100644 index 0000000..2414507 Binary files /dev/null and b/logos/news_logos/pew-research-center.png differ diff --git a/logos/news_logos/portugal-resident.png b/logos/news_logos/portugal-resident.png new file mode 100644 index 0000000..48efdef Binary files /dev/null and b/logos/news_logos/portugal-resident.png differ diff --git a/logos/news_logos/rfi-english.png b/logos/news_logos/rfi-english.png new file mode 100644 index 0000000..3a52f0b Binary files /dev/null and b/logos/news_logos/rfi-english.png differ diff --git a/logos/news_logos/rthk.png b/logos/news_logos/rthk.png new file mode 100644 index 0000000..a6eb2b2 Binary files /dev/null and b/logos/news_logos/rthk.png differ diff --git a/logos/news_logos/smithsonian-magazine.png b/logos/news_logos/smithsonian-magazine.png new file mode 100644 index 0000000..b9d4938 Binary files /dev/null and b/logos/news_logos/smithsonian-magazine.png differ diff --git a/logos/news_logos/the-atlantic.png b/logos/news_logos/the-atlantic.png new file mode 100644 index 0000000..7f15e9c Binary files /dev/null and b/logos/news_logos/the-atlantic.png differ diff --git a/logos/news_logos/the-diplomat.png b/logos/news_logos/the-diplomat.png new file mode 100644 index 0000000..1edc1cf Binary files /dev/null and b/logos/news_logos/the-diplomat.png differ diff --git a/logos/news_logos/the-hindu.png b/logos/news_logos/the-hindu.png new file mode 100644 index 0000000..c675d40 Binary files /dev/null and b/logos/news_logos/the-hindu.png differ diff --git a/logos/news_logos/the-intercept.png b/logos/news_logos/the-intercept.png new file mode 100644 index 0000000..c4cfc60 Binary files /dev/null and b/logos/news_logos/the-intercept.png differ diff --git a/logos/news_logos/the-local-france.png b/logos/news_logos/the-local-france.png new file mode 100644 index 0000000..cd76838 Binary files /dev/null and b/logos/news_logos/the-local-france.png differ diff --git a/logos/news_logos/the-local-italy.png b/logos/news_logos/the-local-italy.png new file mode 100644 index 0000000..4a0c054 Binary files /dev/null and b/logos/news_logos/the-local-italy.png differ diff --git a/logos/news_logos/the-netherlands-and-you.png b/logos/news_logos/the-netherlands-and-you.png new file mode 100644 index 0000000..6e63cd0 Binary files /dev/null and b/logos/news_logos/the-netherlands-and-you.png differ diff --git a/logos/news_logos/the-portugal-news.png b/logos/news_logos/the-portugal-news.png new file mode 100644 index 0000000..7ca241e Binary files /dev/null and b/logos/news_logos/the-portugal-news.png differ diff --git a/logos/news_logos/the-wire.png b/logos/news_logos/the-wire.png new file mode 100644 index 0000000..8c8eb58 Binary files /dev/null and b/logos/news_logos/the-wire.png differ diff --git a/logos/news_logos/theprint.png b/logos/news_logos/theprint.png new file mode 100644 index 0000000..1576c77 Binary files /dev/null and b/logos/news_logos/theprint.png differ diff --git a/logos/news_logos/time-out.png b/logos/news_logos/time-out.png new file mode 100644 index 0000000..e34579b Binary files /dev/null and b/logos/news_logos/time-out.png differ diff --git a/logos/news_logos/trt-world.png b/logos/news_logos/trt-world.png new file mode 100644 index 0000000..c73ba29 Binary files /dev/null and b/logos/news_logos/trt-world.png differ diff --git a/logos/news_logos/u.s.-news-&-world-report.png b/logos/news_logos/u.s.-news-&-world-report.png new file mode 100644 index 0000000..90bed24 Binary files /dev/null and b/logos/news_logos/u.s.-news-&-world-report.png differ diff --git a/logos/news_logos/voa-asia.png b/logos/news_logos/voa-asia.png new file mode 100644 index 0000000..c6e5256 Binary files /dev/null and b/logos/news_logos/voa-asia.png differ diff --git a/logos/news_logos/voice-of-america---voa-news.png b/logos/news_logos/voice-of-america---voa-news.png new file mode 100644 index 0000000..c6e5256 Binary files /dev/null and b/logos/news_logos/voice-of-america---voa-news.png differ diff --git a/logos/sports/league_logos/F1.png b/logos/sports/league_logos/F1.png new file mode 100644 index 0000000..bf70147 Binary files /dev/null and b/logos/sports/league_logos/F1.png differ diff --git a/logos/sports/league_logos/LIV.png b/logos/sports/league_logos/LIV.png new file mode 100644 index 0000000..bcef3da Binary files /dev/null and b/logos/sports/league_logos/LIV.png differ diff --git a/logos/sports/league_logos/NASCAR.png b/logos/sports/league_logos/NASCAR.png new file mode 100644 index 0000000..c884100 Binary files /dev/null and b/logos/sports/league_logos/NASCAR.png differ diff --git a/logos/sports/league_logos/UFC.png b/logos/sports/league_logos/UFC.png new file mode 100644 index 0000000..b481cac Binary files /dev/null and b/logos/sports/league_logos/UFC.png differ diff --git a/logos/tiny_news/69news-wfmz-tv.png b/logos/tiny_news/69news-wfmz-tv.png new file mode 100644 index 0000000..2d64e2a Binary files /dev/null and b/logos/tiny_news/69news-wfmz-tv.png differ diff --git a/logos/tiny_news/8-days.png b/logos/tiny_news/8-days.png new file mode 100644 index 0000000..3f0fa7a Binary files /dev/null and b/logos/tiny_news/8-days.png differ diff --git a/logos/tiny_news/brookings-institution.png b/logos/tiny_news/brookings-institution.png new file mode 100644 index 0000000..76b9c2d Binary files /dev/null and b/logos/tiny_news/brookings-institution.png differ diff --git a/logos/tiny_news/c-span-.png b/logos/tiny_news/c-span-.png new file mode 100644 index 0000000..62a84b8 Binary files /dev/null and b/logos/tiny_news/c-span-.png differ diff --git a/logos/tiny_news/carnegie-europe.png b/logos/tiny_news/carnegie-europe.png new file mode 100644 index 0000000..3689602 Binary files /dev/null and b/logos/tiny_news/carnegie-europe.png differ diff --git a/logos/tiny_news/cheddar.png b/logos/tiny_news/cheddar.png new file mode 100644 index 0000000..5e231fa Binary files /dev/null and b/logos/tiny_news/cheddar.png differ diff --git a/logos/tiny_news/coindesk.png b/logos/tiny_news/coindesk.png new file mode 100644 index 0000000..5e8951e Binary files /dev/null and b/logos/tiny_news/coindesk.png differ diff --git a/logos/tiny_news/dentons.png b/logos/tiny_news/dentons.png new file mode 100644 index 0000000..9a8d076 Binary files /dev/null and b/logos/tiny_news/dentons.png differ diff --git a/logos/tiny_news/dutchnews.nl.png b/logos/tiny_news/dutchnews.nl.png new file mode 100644 index 0000000..f1d590d Binary files /dev/null and b/logos/tiny_news/dutchnews.nl.png differ diff --git a/logos/tiny_news/euractiv.png b/logos/tiny_news/euractiv.png new file mode 100644 index 0000000..0c09234 Binary files /dev/null and b/logos/tiny_news/euractiv.png differ diff --git a/logos/tiny_news/eurasian-times.png b/logos/tiny_news/eurasian-times.png new file mode 100644 index 0000000..274b636 Binary files /dev/null and b/logos/tiny_news/eurasian-times.png differ diff --git a/logos/tiny_news/european-commission.png b/logos/tiny_news/european-commission.png new file mode 100644 index 0000000..9976bbf Binary files /dev/null and b/logos/tiny_news/european-commission.png differ diff --git a/logos/tiny_news/foreign-policy.png b/logos/tiny_news/foreign-policy.png new file mode 100644 index 0000000..1031a12 Binary files /dev/null and b/logos/tiny_news/foreign-policy.png differ diff --git a/logos/tiny_news/gulf-news.png b/logos/tiny_news/gulf-news.png new file mode 100644 index 0000000..a1ddbe2 Binary files /dev/null and b/logos/tiny_news/gulf-news.png differ diff --git a/logos/tiny_news/japan-today.png b/logos/tiny_news/japan-today.png new file mode 100644 index 0000000..b8ba303 Binary files /dev/null and b/logos/tiny_news/japan-today.png differ diff --git a/logos/tiny_news/kcrw.png b/logos/tiny_news/kcrw.png new file mode 100644 index 0000000..844216b Binary files /dev/null and b/logos/tiny_news/kcrw.png differ diff --git a/logos/tiny_news/latestly.png b/logos/tiny_news/latestly.png new file mode 100644 index 0000000..db618cd Binary files /dev/null and b/logos/tiny_news/latestly.png differ diff --git a/logos/tiny_news/markets-insider.png b/logos/tiny_news/markets-insider.png new file mode 100644 index 0000000..e922e04 Binary files /dev/null and b/logos/tiny_news/markets-insider.png differ diff --git a/logos/tiny_news/marketscreener.com.png b/logos/tiny_news/marketscreener.com.png new file mode 100644 index 0000000..eb58b43 Binary files /dev/null and b/logos/tiny_news/marketscreener.com.png differ diff --git a/logos/tiny_news/mingtiandi.png b/logos/tiny_news/mingtiandi.png new file mode 100644 index 0000000..f76609b Binary files /dev/null and b/logos/tiny_news/mingtiandi.png differ diff --git a/logos/tiny_news/mint.png b/logos/tiny_news/mint.png new file mode 100644 index 0000000..e7761a6 Binary files /dev/null and b/logos/tiny_news/mint.png differ diff --git a/logos/tiny_news/new-scientist.png b/logos/tiny_news/new-scientist.png index 35b1019..d1ed3ba 100644 Binary files a/logos/tiny_news/new-scientist.png and b/logos/tiny_news/new-scientist.png differ diff --git a/logos/tiny_news/news-12-bronx.png b/logos/tiny_news/news-12-bronx.png new file mode 100644 index 0000000..7f81775 Binary files /dev/null and b/logos/tiny_news/news-12-bronx.png differ diff --git a/logos/tiny_news/nikkei-asia.png b/logos/tiny_news/nikkei-asia.png new file mode 100644 index 0000000..3b95342 Binary files /dev/null and b/logos/tiny_news/nikkei-asia.png differ diff --git a/logos/tiny_news/oecd.png b/logos/tiny_news/oecd.png new file mode 100644 index 0000000..aa842a3 Binary files /dev/null and b/logos/tiny_news/oecd.png differ diff --git a/logos/tiny_news/pbs-newshour.png b/logos/tiny_news/pbs-newshour.png new file mode 100644 index 0000000..3fa5e37 Binary files /dev/null and b/logos/tiny_news/pbs-newshour.png differ diff --git a/logos/tiny_news/pew-research-center.png b/logos/tiny_news/pew-research-center.png new file mode 100644 index 0000000..baefff8 Binary files /dev/null and b/logos/tiny_news/pew-research-center.png differ diff --git a/logos/tiny_news/portugal-resident.png b/logos/tiny_news/portugal-resident.png new file mode 100644 index 0000000..ac07adb Binary files /dev/null and b/logos/tiny_news/portugal-resident.png differ diff --git a/logos/tiny_news/rfi-english.png b/logos/tiny_news/rfi-english.png new file mode 100644 index 0000000..5831927 Binary files /dev/null and b/logos/tiny_news/rfi-english.png differ diff --git a/logos/tiny_news/rthk.png b/logos/tiny_news/rthk.png new file mode 100644 index 0000000..3e56a38 Binary files /dev/null and b/logos/tiny_news/rthk.png differ diff --git a/logos/tiny_news/smithsonian-magazine.png b/logos/tiny_news/smithsonian-magazine.png new file mode 100644 index 0000000..251416f Binary files /dev/null and b/logos/tiny_news/smithsonian-magazine.png differ diff --git a/logos/tiny_news/the-atlantic.png b/logos/tiny_news/the-atlantic.png new file mode 100644 index 0000000..44929be Binary files /dev/null and b/logos/tiny_news/the-atlantic.png differ diff --git a/logos/tiny_news/the-diplomat.png b/logos/tiny_news/the-diplomat.png new file mode 100644 index 0000000..8e78d7d Binary files /dev/null and b/logos/tiny_news/the-diplomat.png differ diff --git a/logos/tiny_news/the-hindu.png b/logos/tiny_news/the-hindu.png new file mode 100644 index 0000000..ee08f53 Binary files /dev/null and b/logos/tiny_news/the-hindu.png differ diff --git a/logos/tiny_news/the-intercept.png b/logos/tiny_news/the-intercept.png new file mode 100644 index 0000000..2e526a5 Binary files /dev/null and b/logos/tiny_news/the-intercept.png differ diff --git a/logos/tiny_news/the-local-france.png b/logos/tiny_news/the-local-france.png new file mode 100644 index 0000000..357a38b Binary files /dev/null and b/logos/tiny_news/the-local-france.png differ diff --git a/logos/tiny_news/the-local-italy.png b/logos/tiny_news/the-local-italy.png new file mode 100644 index 0000000..ddbaf46 Binary files /dev/null and b/logos/tiny_news/the-local-italy.png differ diff --git a/logos/tiny_news/the-netherlands-and-you.png b/logos/tiny_news/the-netherlands-and-you.png new file mode 100644 index 0000000..7e37817 Binary files /dev/null and b/logos/tiny_news/the-netherlands-and-you.png differ diff --git a/logos/tiny_news/the-portugal-news.png b/logos/tiny_news/the-portugal-news.png new file mode 100644 index 0000000..7370822 Binary files /dev/null and b/logos/tiny_news/the-portugal-news.png differ diff --git a/logos/tiny_news/the-wire.png b/logos/tiny_news/the-wire.png new file mode 100644 index 0000000..074d8ca Binary files /dev/null and b/logos/tiny_news/the-wire.png differ diff --git a/logos/tiny_news/theprint.png b/logos/tiny_news/theprint.png new file mode 100644 index 0000000..26f4980 Binary files /dev/null and b/logos/tiny_news/theprint.png differ diff --git a/logos/tiny_news/time-out.png b/logos/tiny_news/time-out.png new file mode 100644 index 0000000..24940f1 Binary files /dev/null and b/logos/tiny_news/time-out.png differ diff --git a/logos/tiny_news/trt-world.png b/logos/tiny_news/trt-world.png new file mode 100644 index 0000000..f1868bd Binary files /dev/null and b/logos/tiny_news/trt-world.png differ diff --git a/logos/tiny_news/u.s.-news-&-world-report.png b/logos/tiny_news/u.s.-news-&-world-report.png new file mode 100644 index 0000000..b9e2766 Binary files /dev/null and b/logos/tiny_news/u.s.-news-&-world-report.png differ diff --git a/logos/tiny_news/voa-asia.png b/logos/tiny_news/voa-asia.png new file mode 100644 index 0000000..717ec57 Binary files /dev/null and b/logos/tiny_news/voa-asia.png differ diff --git a/logos/tiny_news/voice-of-america---voa-news.png b/logos/tiny_news/voice-of-america---voa-news.png new file mode 100644 index 0000000..717ec57 Binary files /dev/null and b/logos/tiny_news/voice-of-america---voa-news.png differ diff --git a/logos/ufc/blank.rtf b/logos/ufc/blank.rtf new file mode 100644 index 0000000..15e538c --- /dev/null +++ b/logos/ufc/blank.rtf @@ -0,0 +1,6 @@ +{\rtf1\ansi\ansicpg1252\cocoartf2513 +\cocoatextscaling0\cocoaplatform0{\fonttbl} +{\colortbl;\red255\green255\blue255;} +{\*\expandedcolortbl;;} +\margl1440\margr1440\vieww10800\viewh8400\viewkind0 +} \ No newline at end of file diff --git a/logos/ufc_countries/blank.rtf b/logos/ufc_countries/blank.rtf new file mode 100644 index 0000000..15e538c --- /dev/null +++ b/logos/ufc_countries/blank.rtf @@ -0,0 +1,6 @@ +{\rtf1\ansi\ansicpg1252\cocoartf2513 +\cocoatextscaling0\cocoaplatform0{\fonttbl} +{\colortbl;\red255\green255\blue255;} +{\*\expandedcolortbl;;} +\margl1440\margr1440\vieww10800\viewh8400\viewkind0 +} \ No newline at end of file diff --git a/logos/ufc_past/blank.rtf b/logos/ufc_past/blank.rtf new file mode 100644 index 0000000..15e538c --- /dev/null +++ b/logos/ufc_past/blank.rtf @@ -0,0 +1,6 @@ +{\rtf1\ansi\ansicpg1252\cocoartf2513 +\cocoatextscaling0\cocoaplatform0{\fonttbl} +{\colortbl;\red255\green255\blue255;} +{\*\expandedcolortbl;;} +\margl1440\margr1440\vieww10800\viewh8400\viewkind0 +} \ No newline at end of file diff --git a/logos/unknown.png b/logos/unknown.png new file mode 100644 index 0000000..c533209 Binary files /dev/null and b/logos/unknown.png differ diff --git a/logos/up-tiny.png b/logos/up-tiny.png new file mode 100644 index 0000000..64ccf3b Binary files /dev/null and b/logos/up-tiny.png differ diff --git a/logos/up-tiny2.png b/logos/up-tiny2.png new file mode 100644 index 0000000..c2c0dc0 Binary files /dev/null and b/logos/up-tiny2.png differ diff --git a/server.py b/server.py index 2d43ca4..dc089a5 100755 --- a/server.py +++ b/server.py @@ -9,7 +9,9 @@ from flask import Flask, render_template, request from stockTicker import StockTicker from werkzeug.utils import secure_filename import os +import pytz import datetime +from datetime import timedelta import threading import csv import pexpect @@ -119,7 +121,7 @@ app = Flask(__name__) def index(): global command all_features = ['Current Weather','Daily Forecast','News', 'Sports (Upcoming Games)','Sports (Past Games)','Sports (Live Games)', - 'Sports (Team Stats)','Custom Images', 'Custom GIFs', 'Custom Messages', 'Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices', 'Movies'] + 'Sports (Team Stats)','Custom Images', 'Custom GIFs', 'Custom Messages', 'Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices', 'Movies', 'IPO Calendar'] global professional @@ -152,7 +154,13 @@ def index(): movie_api = f.readlines() except: movie_api = '' - + + try: + with open('ipo_api_key.txt', 'r') as f: + ipo_api = f.readlines() + except: + ipo_api = '' + with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'r') as f: wifiline = f.readlines() @@ -160,7 +168,7 @@ def index(): timeString = now.strftime("%Y-%m-%d %H:%M") logos_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos') LogoList = os.listdir(logos_path) - + f = open('csv/stocks_settings.json', 'r') stocks_settings = json.load(f) f.close() @@ -180,6 +188,10 @@ def index(): f= open('csv/movie_settings.json', 'r') movie_settings = json.load(f) f.close() + + f= open('csv/ipo_settings.json', 'r') + ipo_settings = json.load(f) + f.close() f = open('csv/forex_settings.json', 'r') forex_settings = json.load(f) @@ -229,7 +241,12 @@ def index(): general_settings = json.load(f) f.close() - + try: + f = open('csv/scheduler.json','r') + scheduler_settings = json.load(f) + f.close() + except: + scheduler_settings = {"shutdown": {"hour": "00", "minute": "00", "enabled": False}, "reboot":{"hour": "00", "minute": "00", "enabled": False}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}} try: # incase this doesnt exist api_keys = api_key2[1] @@ -240,7 +257,12 @@ def index(): movie_api_key = movie_api[0] except: movie_api_key = '' - + + try: + ipo_api_key = ipo_api[0] + except: + ipo_api_key = '' + try: wifi_SSID = wifiline[5][6:].replace('"','') except: @@ -266,6 +288,7 @@ def index(): 'current_weather': current_weather, 'daily_weather': daily_weather, 'movie_settings': movie_settings, + 'ipo_settings': ipo_settings, 'news_settings': news_settings, 'upcoming_games': upcoming_games, 'past_games': past_games, @@ -278,8 +301,10 @@ def index(): 'general_settings':general_settings, 'api_keys':api_keys, 'movie_api_key':movie_api_key, + 'ipo_api_key':ipo_api_key, 'wifi_SSID':wifi_SSID, - 'wifi_PSK':wifi_PSK + 'wifi_PSK':wifi_PSK, + 'scheduler_settings':scheduler_settings } @@ -287,15 +312,109 @@ def index(): +def scheduled_brightness(): + try: + while True: + try: + f = open('csv/scheduler.json','r') + schedules = json.load(f) + f.close() + except: + schedules = {"shutdown": {"hour": "00", "minute": "00", "enabled": False}, "reboot":{"hour": "00", "minute": "00", "enabled": False}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}} + + timezone_brightness = schedules['timezone'] + + brightness1_hour = schedules['brightness1']['hour'] + brightness1_minute = schedules['brightness1']['minute'] + brightness1_bright = schedules['brightness1']['bright'] + brightness1_enabled = schedules['brightness1']['enabled'] + + brightness2_hour = schedules['brightness2']['hour'] + brightness2_minute = schedules['brightness2']['minute'] + brightness2_bright = schedules['brightness2']['bright'] + brightness2_enabled = schedules['brightness2']['enabled'] + + brightness3_hour = schedules['brightness3']['hour'] + brightness3_minute = schedules['brightness3']['minute'] + brightness3_bright = schedules['brightness3']['bright'] + brightness3_enabled = schedules['brightness3']['enabled'] + + brightness4_hour = schedules['brightness4']['hour'] + brightness4_minute = schedules['brightness4']['minute'] + brightness4_bright = schedules['brightness4']['bright'] + brightness4_enabled = schedules['brightness4']['enabled'] + + try: + if brightness1_enabled and datetime.datetime.now(pytz.timezone(timezone_brightness)).strftime("%H:%M") == brightness1_hour+':'+brightness1_minute: + brightness = max(min(int(brightness1_bright), 10), 1) + ticker.sendline(str(brightness-1)) + f = open('csv/general_settings.json', 'r') + general_settings = json.load(f) + f.close() + general_settings['brightness'] = int(brightness) + f = open('csv/general_settings.json', 'w') + json.dump(general_settings, f) + f.close() + except: + pass + try: + if brightness2_enabled and datetime.datetime.now(pytz.timezone(timezone_brightness)).strftime("%H:%M") == brightness2_hour+':'+brightness2_minute: + brightness = max(min(int(brightness2_bright), 10), 1) + ticker.sendline(str(brightness-1)) + f = open('csv/general_settings.json', 'r') + general_settings = json.load(f) + f.close() + general_settings['brightness'] = int(brightness) + f = open('csv/general_settings.json', 'w') + json.dump(general_settings, f) + f.close() + except: + pass + try: + if brightness3_enabled and datetime.datetime.now(pytz.timezone(timezone_brightness)).strftime("%H:%M") == brightness3_hour+':'+brightness3_minute: + brightness = max(min(int(brightness3_bright), 10), 1) + ticker.sendline(str(brightness-1)) + f = open('csv/general_settings.json', 'r') + general_settings = json.load(f) + f.close() + general_settings['brightness'] = int(brightness) + f = open('csv/general_settings.json', 'w') + json.dump(general_settings, f) + f.close() + except: + pass + try: + if brightness4_enabled and datetime.datetime.now(pytz.timezone(timezone_brightness)).strftime("%H:%M") == brightness4_hour+':'+brightness4_minute: + brightness = max(min(int(brightness4_bright), 10), 1) + ticker.sendline(str(brightness-1)) + f = open('csv/general_settings.json', 'r') + general_settings = json.load(f) + f.close() + general_settings['brightness'] = int(brightness) + f = open('csv/general_settings.json', 'w') + json.dump(general_settings, f) + f.close() + except: + pass + time.sleep(20) + except: + pass + +scheduled_b = Process(target=scheduled_brightness) +scheduled_b.start() + + + def save_displaying(input_settings): global professional all_settings = ['Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices', 'Current Weather', 'Daily Forecast', 'News', 'Sports (Upcoming Games)', 'Sports (Past Games)', - 'Sports (Live Games)', 'Sports (Team Stats)', 'Custom Images', 'Custom GIFs', 'Custom Messages', 'Movies'] + 'Sports (Live Games)', 'Sports (Team Stats)', 'Custom Images', 'Custom GIFs', 'Custom Messages', 'Movies', 'IPO Calendar'] professional = len(input_settings) == 2 if professional: - all_settings = ['Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices', 'Current Weather', 'News', 'Daily Forecast', 'Sports (Upcoming Games)', 'Sports (Past Games)', 'Sports (Team Stats)', 'Sports (Live Games)', 'Custom Messages', 'Custom Images', 'Movies'] + all_settings = ['Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices', 'Current Weather', 'News', 'Daily Forecast', 'Sports (Upcoming Games)', + 'Sports (Past Games)', 'Sports (Team Stats)', 'Sports (Live Games)', 'Custom Messages', 'Custom Images', 'Movies', 'IPO Calendar'] positions = [] @@ -337,7 +456,13 @@ def start(): ticker_stopped = False #api_caller.sendline('A') - + + global scheduled_b + if scheduled_b.is_alive(): + scheduled_b.terminate() + scheduled_b = Process(target=scheduled_brightness) + scheduled_b.start() + ticker.sendline('K') ticker.sendline('A') @@ -374,7 +499,10 @@ def stop(): #api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 api_caller.py") #api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 database_caller.py") displaying_screensaver = False - + + + scheduled_b.terminate() + return index() @app.route("/update", methods=['PUT','POST']) @@ -437,6 +565,8 @@ def save(): save_news_settings(input_settings) elif feature == 'Movies': save_movie_settings(input_settings) + elif feature == 'IPO Calendar': + save_ipo_settings(input_settings) elif 'Sports' in feature: save_sports_settings(input_settings) @@ -660,7 +790,145 @@ def saveMovieAPIKey(): return index() +@app.route("/saveIpoAPIKey", methods = ['PUT', 'POST']) +def saveIpoAPIKey(): + data= request.data.decode('utf-8') + settings = json.loads(data) + + key = settings['api_key'] + + with open('ipo_api_key.txt', 'w') as f: + f.write(str(key)) + + return index() + +@app.route("/savePortfolioSettings", methods = ['PUT', 'POST']) +def savePortfolioSettings(): + + data= request.data.decode('utf-8') + settings = json.loads(data) + + #THIS IS TO CREATE PORTFOLIO JSON FILE IF IT DOESN'T EXIST + initialize_json = '{"symbols":{}}' + if 'portfolio_settings.json' not in os.listdir('csv/'): + with open('csv/portfolio_settings.json', 'w') as f: + f.write(initialize_json) + + try: + f = open('csv/portfolio_settings.json') + portfolio = json.load(f) + f.close() + + shares1 = settings['shares'] + cost1 = settings['cost'] + symbol1 = settings['symbol'] + + days1 = settings['days'] + day_start = datetime.datetime.strptime(str(days1), "%Y-%m-%d") + day_today = datetime.datetime.strptime(datetime.datetime.now(pytz.utc).strftime("%Y-%m-%d"), "%Y-%m-%d") + days1 = str((day_today - day_start).days) + + portfolio['symbols'][symbol1] = {'shares':shares1, 'day':days1, 'cost':cost1} + + f = open("csv/portfolio_settings.json", 'w+') + json.dump(portfolio, f) + f.close() + except: + pass + + return index() + +@app.route("/savePortfolioCryptoSettings", methods = ['PUT', 'POST']) +def savePortfolioCryptoSettings(): + + data= request.data.decode('utf-8') + settings = json.loads(data) + + #THIS IS TO CREATE PORTFOLIO JSON FILE IF IT DOESN'T EXIST + initialize_json = '{"symbols":{}}' + if 'portfolio_crypto_settings.json' not in os.listdir('csv/'): + with open('csv/portfolio_crypto_settings.json', 'w') as f: + f.write(initialize_json) + + try: + f = open('csv/portfolio_crypto_settings.json') + portfolio = json.load(f) + f.close() + + shares1 = settings['shares'] + cost1 = settings['cost'] + symbol1 = settings['symbol'] + + days1 = settings['days'] + day_start = datetime.datetime.strptime(str(days1), "%Y-%m-%d") + day_today = datetime.datetime.strptime(datetime.datetime.now(pytz.utc).strftime("%Y-%m-%d"), "%Y-%m-%d") + days1 = str((day_today - day_start).days) + + portfolio['symbols'][symbol1] = {'shares':shares1, 'day':days1, 'cost':cost1} + + f = open("csv/portfolio_crypto_settings.json", 'w+') + json.dump(portfolio, f) + f.close() + except: + pass + + return index() + + +@app.route("/deletePortfolioSettings", methods = ['PUT', 'POST']) +def deletePortfolioSettings(): + + data= request.data.decode('utf-8') + settings = json.loads(data) + + try: + g = open('csv/portfolio_settings.json') + portfolio = json.load(g) + g.close() + + symbol = settings + # DELETE SYMBOLS FUNCTION + try: + portfolio['symbols'].pop(symbol) + except: + pass + + f = open("csv/portfolio_settings.json", 'w+') + json.dump(portfolio, f) + f.close() + except: + pass + + return index() + +@app.route("/deletePortfolioCryptoSettings", methods = ['PUT', 'POST']) +def deletePortfolioCryptoSettings(): + + data= request.data.decode('utf-8') + settings = json.loads(data) + + try: + g = open('csv/portfolio_crypto_settings.json') + portfolio = json.load(g) + g.close() + + symbol = settings + # DELETE SYMBOLS FUNCTION + try: + portfolio['symbols'].pop(symbol) + except: + pass + + f = open("csv/portfolio_crypto_settings.json", 'w+') + json.dump(portfolio, f) + f.close() + except: + pass + + return index() + + @app.route("/screensaver", methods = ['PUT', 'POST']) def screensaver(): global displaying_screensaver @@ -706,7 +974,7 @@ def screensaver(): else: #default in case user hasnt set one yet screensaver_p = DummyProcess() - + scheduled_b.terminate() displaying_screensaver = True return index() @@ -746,7 +1014,10 @@ def save_trade_settings(input_settings): current_settings['point'] = input_settings['point'] current_settings['logos'] = input_settings['logos'] current_settings['title'] = input_settings['title'] - + if input_settings['feature'] == 'Stocks': + current_settings['prepost'] = input_settings['prepost'] + if input_settings['feature'] == 'Stocks' or input_settings['feature'] == 'Crypto': + current_settings['chart'] = input_settings['chart'] current_settings = combine_dict(current_settings, input_settings['symbols'], 'symbols') @@ -759,6 +1030,8 @@ def save_trade_settings(input_settings): if any([current_settings['symbols'][k] == [] for k in input_settings['symbols']]): last_updates[input_settings['feature'].lower()]['force'] = True + if input_settings['feature'] == 'Stocks': + last_updates['prepost']['force'] = True @@ -877,8 +1150,34 @@ def save_movie_settings(input_settings): f = open('csv/last_updates.json', 'w') json.dump(last_updates, f) f.close() + + +def save_ipo_settings(input_settings): + filename = 'ipo_settings.json' + f = open('csv/' + filename, 'r') + current_settings = json.load(f) + f.close() + current_settings['speed'] = input_settings['speed'].lower() + current_settings['speed2'] = input_settings['speed2'].lower() + current_settings['animation'] = input_settings['animation'].lower() + current_settings['title'] = input_settings['title'] + + f = open('csv/' + filename, 'w') + json.dump(current_settings, f) + f.close() + #api_caller.sendline('n') + f = open('csv/last_updates.json', 'r') + last_updates = json.load(f) + f.close() + last_updates['ipo']['force'] = True + + f = open('csv/last_updates.json', 'w') + json.dump(last_updates, f) + f.close() + + def save_sports_settings(input_settings): feature = input_settings['feature'] @@ -970,9 +1269,70 @@ def shutdown(): os.system("sudo shutdown now") return index() + +@app.route("/saveSchedulerSettings", methods = ['PUT', 'POST']) +def saveSchedulerSettings(): + data= request.data.decode('utf-8') + input_settings = json.loads(data) + + initialize_json = '{"shutdown": {"hour": "00", "minute": "00", "enabled": false}, "reboot":{"hour": "00", "minute": "00", "enabled": false}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}}' + + if 'scheduler.json' not in os.listdir('csv/'): + with open('csv/scheduler.json', 'w') as f: + f.write(initialize_json) + + try: + with open('csv/scheduler.json','r') as f: + scheduler_settings = json.load(f) + except: + scheduler_settings = {"shutdown": {"hour": "00", "minute": "00", "enabled": False}, "reboot":{"hour": "00", "minute": "00", "enabled": False}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}} + + scheduler_settings['shutdown']['hour'] = input_settings['shutdown_hour'] + scheduler_settings['shutdown']['minute'] = input_settings['shutdown_minute'] + scheduler_settings['shutdown']['enabled'] = input_settings['shutdown_enabled'] + + scheduler_settings['reboot']['hour'] = input_settings['reboot_hour'] + scheduler_settings['reboot']['minute'] = input_settings['reboot_minute'] + scheduler_settings['reboot']['enabled'] = input_settings['reboot_enabled'] + + scheduler_settings['brightness1']['hour'] = input_settings['brightness1_hour'] + scheduler_settings['brightness1']['minute'] = input_settings['brightness1_minute'] + scheduler_settings['brightness1']['enabled'] = input_settings['brightness1_enabled'] + scheduler_settings['brightness1']['bright'] = input_settings['brightness1_bright'] + + scheduler_settings['brightness2']['hour'] = input_settings['brightness2_hour'] + scheduler_settings['brightness2']['minute'] = input_settings['brightness2_minute'] + scheduler_settings['brightness2']['enabled'] = input_settings['brightness2_enabled'] + scheduler_settings['brightness2']['bright'] = input_settings['brightness2_bright'] + + scheduler_settings['brightness3']['hour'] = input_settings['brightness3_hour'] + scheduler_settings['brightness3']['minute'] = input_settings['brightness3_minute'] + scheduler_settings['brightness3']['enabled'] = input_settings['brightness3_enabled'] + scheduler_settings['brightness3']['bright'] = input_settings['brightness3_bright'] + + scheduler_settings['brightness4']['hour'] = input_settings['brightness4_hour'] + scheduler_settings['brightness4']['minute'] = input_settings['brightness4_minute'] + scheduler_settings['brightness4']['enabled'] = input_settings['brightness4_enabled'] + scheduler_settings['brightness4']['bright'] = input_settings['brightness4_bright'] + + scheduler_settings['timezone'] = input_settings['timezone'] + + with open('csv/scheduler.json', 'w') as f: + json.dump(scheduler_settings,f) + + f = open('csv/last_updates.json', 'r') + last_updates = json.load(f) + f.close() + + last_updates['scheduler']['force'] = True + + f = open('csv/last_updates.json', 'w') + json.dump(last_updates, f) + f.close() + + return index() - diff --git a/setup_config_files.sh b/setup_config_files.sh index ea6bd1f..1a527be 100755 --- a/setup_config_files.sh +++ b/setup_config_files.sh @@ -13,15 +13,15 @@ rm *.json touch crypto_settings.json last_updates.json system_info.json touch league_tables.json mkdir sports -touch current_weather.json stocks_settings.json daily_weather.json live_games.json live_mlb.json live_mls.json live_nba.json live_nfl.json live_nhl.json live_pl.json commodities_settings.json indices_settings.json movie_settings.json -touch display_settings.json message_settings.json upcoming_games.json forex_settings.json -touch GIF_settings.json news_settings.json image_settings.json past_games.json general_settings.json +touch current_weather.json stocks_settings.json daily_weather.json live_games.json live_mlb.json live_mls.json live_nba.json live_nfl.json live_nhl.json live_pl.json commodities_settings.json indices_settings.json movie_settings.json ipo_settings.json +touch display_settings.json message_settings.json upcoming_games.json forex_settings.json prepost_settings.json scheduler.json +touch GIF_settings.json news_settings.json image_settings.json past_games.json general_settings.json portfolio_settings.json portfolio_crypto_settings.json -filenames="crypto_settings.json last_updates.json league_tables.json current_weather.json stocks_settings.json daily_weather.json live_games.json live_mlb.json live_mls.json live_nba.json live_nfl.json live_nhl.json live_pl.json commodities_settings.json indices_settings.json movie_settings.json display_settings.json message_settings.json upcoming_games.json forex_settings.json GIF_settings.json news_settings.json image_settings.json past_games.json" +filenames="crypto_settings.json last_updates.json league_tables.json current_weather.json stocks_settings.json daily_weather.json live_games.json live_mlb.json live_mls.json live_nba.json live_nfl.json live_nhl.json live_pl.json commodities_settings.json indices_settings.json movie_settings.json ipo_settings.json display_settings.json message_settings.json upcoming_games.json forex_settings.json GIF_settings.json news_settings.json image_settings.json past_games.json portfolio_settings.json portfolio_crypto_settings.json prepost_settings.json scheduler.json" echo '{"update_available": false, "first_boot": true}' >> system_info.json echo [\"Standard\", [[\"Stocks\", \"Crypto\", \"Forex\"]]] >> display_settings.json -echo '{"stocks": {"time": "07/03/2022 12:33:06", "force": true}, "crypto": {"time": "07/03/2022 12:28:51", "force": true}, "news": {"time": "07/03/2022 12:28:51", "force": true}, "weather": {"time": "07/03/2022 12:28:51", "force": true}, "forex": {"time": "07/03/2022 12:28:51", "force": true}, "sports_l": {"time": "07/03/2022 12:32:46", "force": true}, "sports_p": {"time": "07/03/2022 12:32:26", "force": true}, "sports_u": {"time": "07/03/2022 12:31:55", "force": true}, "sports_t": {"time": "07/03/2022 12:32:56", "force": true}, "commodities": {"time": "07/03/2022 12:32:56", "force": true}, "indices": {"time": "07/03/2022 12:32:56", "force": true}, "movies": {"time": "07/03/2022 12:32:56", "force": true}}' >> last_updates.json +echo '{"scheduler":{"force": false}, "stocks": {"time": "07/03/2022 12:33:06", "force": true}, "crypto": {"time": "07/03/2022 12:28:51", "force": true}, "news": {"time": "07/03/2022 12:28:51", "force": true}, "weather": {"time": "07/03/2022 12:28:51", "force": true}, "forex": {"time": "07/03/2022 12:28:51", "force": true}, "sports_l": {"time": "07/03/2022 12:32:46", "force": true}, "sports_p": {"time": "07/03/2022 12:32:26", "force": true}, "sports_u": {"time": "07/03/2022 12:31:55", "force": true}, "sports_t": {"time": "07/03/2022 12:32:56", "force": true}, "commodities": {"time": "07/03/2022 12:32:56", "force": true}, "indices": {"time": "07/03/2022 12:32:56", "force": true}, "movies": {"time": "07/03/2022 12:32:56", "force": true}, "ipo": {"time": "05/10/2022 02:31:40", "force": false}, "prepost": {"time": "05/10/2022 02:31:40", "force": false}}' >> last_updates.json echo '{"feature": "Stocks", "speed": "medium","speed2": "medium", "animation": "down", "percent": false, "point": true, "logos": true, "chart": false, "title": true, "symbols": {"ETH,USD": {"current": "2629.32", "24hr_change": "-27.6432", "percent_change": "-1.04"}, "BTC,USD": {"current": "38161.00", "24hr_change": "-50.8386", "percent_change": "-0.13"}, "BNB,USD": {"current": "372.57", "24hr_change": "0.4140", "percent_change": "0.11"}, "ADA,BTC": {"current": "0.0000", "24hr_change": "-0.0000", "percent_change": "-3.74"}}}' >> crypto_settings.json @@ -30,7 +30,7 @@ echo '{"feature": "Stocks", "speed": "fast", "speed2": "fast", "animation": "dow echo '{"feature": "Stocks", "speed": "fast", "speed2": "slow", "animation": "up", "percent": true, "point": true, "logos": true, "chart": false, "title": true, "symbols": {"^HSI": {"name": "HSI", "current": "18083.06", "point_change": "1003.55", "percent_change": "5.88"}, "^GSPC": {"name": "S&P 500", "current": "3790.93", "point_change": "112.50", "percent_change": "3.06"}, "^RUT": {"name": "RUSSELL 2000", "current": "1775.77", "point_change": "66.90", "percent_change": "3.91"}, "^GDAXI": {"name": "DAX", "current": "12648.95", "point_change": "-21.53", "percent_change": "-0.17"}, "^FTSE": {"name": "FTSE 100", "current": "7058.68", "point_change": "-27.82", "percent_change": "-0.39"}, "^FCHI": {"name": "CAC 40", "current": "6031.45", "point_change": "-8.24", "percent_change": "-0.14"}, "399001.SZ": {"name": "SZSE", "current": "10778.61", "point_change": "-140.83", "percent_change": "-1.29"}, "^STOXX50E": {"name": "STOXX 50", "current": "3476.55", "point_change": "-7.93", "percent_change": "-0.23"}, "^AXJO": {"name": "ASX 200", "current": "6815.70", "point_change": "116.40", "percent_change": "1.74"}, "^DJI": {"name": "DOW JONES", "current": "30316.32", "point_change": "825.43", "percent_change": "2.80"}, "^STOXX": {"name": "STOXX 600", "current": "402.33", "point_change": "-0.70", "percent_change": "-0.17"}}}' >> indices_settings.json echo '{"feature": "Sports (Team Stats)", "speed": "medium", "speed2": "medium","animation": "down", "title": true, "leagues": {}}' >> league_tables.json echo {\"feature\": \"Current Weather\", \"speed\": \"medium\", \"animation\": \"down\", \"temp\": \"celsius\", \"wind_speed\": \"miles/sec\", \"colour\": \"white\", \"city_colour\": \"yellow\", \"title\": true, \"locations\": {}, \"current_weather\": true} >> current_weather.json -echo '{"feature": "Stocks", "speed": "medium", "speed2": "medium", "animation": "down", "percent": false, "point": true, "logos": true, "chart": false, "title": true, "symbols": {"AAPL": {"current": "164.02", "change": "-1.59", "percent_change": "-0.97"}, "MSFT": {"current": "288.29", "change": "-1.32", "percent_change": "-0.46"}, "GOOG": {"current": "2586.74", "change": "-34.01", "percent_change": "-1.31"}, "NFLX": {"current": "380.52", "change": "-7.59", "percent_change": "-1.99"}}}' >> stocks_settings.json +echo '{"feature": "Stocks", "speed": "medium", "speed2": "medium", "animation": "down", "percent": false, "point": true, "logos": true, "chart": false, "title": true, "symbols": {"AAPL": {"current": "164.02", "change": "-1.59", "percent_change": "-0.97"}, "MSFT": {"current": "288.29", "change": "-1.32", "percent_change": "-0.46"}, "GOOG": {"current": "2586.74", "change": "-34.01", "percent_change": "-1.31"}, "NFLX": {"current": "380.52", "change": "-7.59", "percent_change": "-1.99"}}, "prepost": false}' >> stocks_settings.json echo {\"feature\": \"Current Weather\", \"speed\": \"medium\", \"animation\": \"down\", \"temp\": \"celsius\", \"wind_speed\": \"miles/sec\", \"colour\": \"white\", \"city_colour\": \"yellow\", \"title\": true, \"locations\": {}, \"current_weather\": true} >> daily_weather.json echo '{"feature": "Sports (Live Games)", "speed": "medium", "speed2": "medium", "animation": "down", "title": true, "leagues": {}}' >> live_games.json echo '{"feature": "Sports (Live Games)", "speed": "medium", "speed2": "medium", "animation": "down", "title": true, "leagues": {"MLB": [[{"home_team": "Columbus Blue Jackets", "home_score": "4", "away_team": "Buffalo Sabres", "away_score": "9", "time": "Final", "date": "2022-12-08", "isLive": "post"}, {"home_team": "Philadelphia Flyers", "home_score": "1", "away_team": "Washington Capitals", "away_score": "4", "time": "Final", "date": "2022-12-08", "isLive": "post"}, {"home_team": "Calgary Flames", "home_score": "5", "away_team": "Minnesota Wild", "away_score": "3", "time": "Final", "date": "2022-12-08", "isLive": "post"}, {"home_team": "Colorado Avalanche", "home_score": "0", "away_team": "Boston Bruins", "away_score": "4", "time": "Final", "date": "2022-12-08", "isLive": "post"}, {"home_team": "Edmonton Oilers", "home_score": "8", "away_team": "Arizona Coyotes", "away_score": "2", "time": "Final", "date": "2022-12-08", "isLive": "post"}, {"home_team": "Vegas Golden Knights", "home_score": "1", "away_team": "New York Rangers", "away_score": "5", "time": "Final", "date": "2022-12-08", "isLive": "post"}, {"home_team": "San Jose Sharks", "home_score": "5", "away_team": "Vancouver Canucks", "away_score": "6", "time": "Final/OT", "date": "2022-12-08", "isLive": "post"}], false, "no_live", "no_upcoming"]}}' >> live_mlb.json @@ -47,6 +47,11 @@ echo '{"feature": "News", "speed": "medium", "speed2": "medium", "animation": "d echo '{"speed": "slow", "speed2": "medium","animation": "down", "title": true, "pause": "/", "images": []}' >> image_settings.json echo '{"feature": "Sports (Past Games)", "speed2": "medium", "speed": "medium", "animation": "down", "title": true, "leagues": {}}' >> past_games.json echo '{"feature": "Movies", "speed": "fast", "speed2": "fast", "animation": "continuous", "category": "Popular All", "title": true, "movies": [{"title": "Avatar: The Way of Water", "language": "EN", "votes": "8.1", "date": "2022-12-14", "media_type": "Movie", "genre": ["Sci-Fi", "Action", "Adventure"], "backdrop": "198vrF8k7mfQ4FjDJsBmdQcaiyq.jpg", "logo": "https://image.tmdb.org/t/p/w500/198vrF8k7mfQ4FjDJsBmdQcaiyq.jpg"}, {"title": "Violent Night", "language": "EN", "votes": "7.3", "date": "2022-11-30", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime", "Thriller"], "backdrop": "g9Kb3RaLjsybI1jpqHQ3QZTCYpB.jpg", "logo": "https://image.tmdb.org/t/p/w500/g9Kb3RaLjsybI1jpqHQ3QZTCYpB.jpg"}, {"title": "Avatar", "language": "EN", "votes": "7.5", "date": "2009-12-15", "media_type": "Movie", "genre": ["Action", "Adventure", "Fantasy", "Sci-Fi"], "backdrop": "Yc9q6QuWrMp9nuDm5R8ExNqbEq.jpg", "logo": "https://image.tmdb.org/t/p/w500/Yc9q6QuWrMp9nuDm5R8ExNqbEq.jpg"}, {"title": "The Banshees of Inisherin", "language": "EN", "votes": "7.7", "date": "2022-10-21", "media_type": "Movie", "genre": ["Drama", "Comedy"], "backdrop": "9Md4CqzUGDtK5oEkRRvozLkGc9d.jpg", "logo": "https://image.tmdb.org/t/p/w500/9Md4CqzUGDtK5oEkRRvozLkGc9d.jpg"}, {"title": "Wednesday", "language": "EN", "votes": "8.8", "date": "2022-11-23", "media_type": "Tv", "genre": ["Sci-Fi & Fantasy", "Mystery", "Comedy"], "backdrop": "iHSwvRVsRyxpX7FE7GbviaDvgGZ.jpg", "logo": "https://image.tmdb.org/t/p/w500/iHSwvRVsRyxpX7FE7GbviaDvgGZ.jpg"}, {"title": "1923", "language": "EN", "votes": "8.8", "date": "2022-12-18", "media_type": "Tv", "genre": ["Drama", "Western"], "backdrop": "9I6LgZ5110ycg4pyobJxGTFWFCF.jpg", "logo": "https://image.tmdb.org/t/p/w500/9I6LgZ5110ycg4pyobJxGTFWFCF.jpg"}, {"title": "The Recruit", "language": "EN", "votes": "7.2", "date": "2022-12-16", "media_type": "Tv", "genre": ["Drama", "Crime"], "backdrop": "rey2eh6752C2UbGYRileKk1PVTo.jpg", "logo": "https://image.tmdb.org/t/p/w500/rey2eh6752C2UbGYRileKk1PVTo.jpg"}, {"title": "Black Adam", "language": "EN", "votes": "7.2", "date": "2022-10-19", "media_type": "Movie", "genre": ["Action", "Fantasy", "Sci-Fi"], "backdrop": "bQXAqRx2Fgc46uCVWgoPz5L5Dtr.jpg", "logo": "https://image.tmdb.org/t/p/w500/bQXAqRx2Fgc46uCVWgoPz5L5Dtr.jpg"}, {"title": "Nanny", "language": "EN", "votes": "5.4", "date": "2022-11-23", "media_type": "Movie", "genre": ["Horror", "Drama"], "backdrop": "nfuPlOK6ywGzKGb0yf7VJKyTFWb.jpg", "logo": "https://image.tmdb.org/t/p/w500/nfuPlOK6ywGzKGb0yf7VJKyTFWb.jpg"}, {"title": "Tom Clancys Jack Ryan", "language": "EN", "votes": "7.7", "date": "2018-08-30", "media_type": "Tv", "genre": ["Action & Adventure", "Drama", "War & Politics"], "backdrop": "6ovk8nrrSmN1ieT14zBAxcHbMU7.jpg", "logo": "https://image.tmdb.org/t/p/w500/6ovk8nrrSmN1ieT14zBAxcHbMU7.jpg"}, {"title": "High Heat", "language": "EN", "votes": "6.5", "date": "2022-12-16", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime"], "backdrop": "gjNM0odqkq5F7V58OjfTxPJ9p9Z.jpg", "logo": "https://image.tmdb.org/t/p/w500/gjNM0odqkq5F7V58OjfTxPJ9p9Z.jpg"}, {"title": "A Not So Merry Christmas", "language": "ES", "votes": "4.8", "date": "2022-12-20", "media_type": "Movie", "genre": ["Comedy"], "backdrop": "8uyJzaiGbiezZ9K48Cy5wXeqnYw.jpg", "logo": "https://image.tmdb.org/t/p/w500/8uyJzaiGbiezZ9K48Cy5wXeqnYw.jpg"}, {"title": "Guillermo del Toros Pinocchio", "language": "EN", "votes": "8.5", "date": "2022-11-09", "media_type": "Movie", "genre": ["Animation", "Fantasy", "Drama"], "backdrop": "e782pDRAlu4BG0ahd777n8zfPzZ.jpg", "logo": "https://image.tmdb.org/t/p/w500/e782pDRAlu4BG0ahd777n8zfPzZ.jpg"}, {"title": "His Dark Materials", "language": "EN", "votes": "8.0", "date": "2019-11-03", "media_type": "Tv", "genre": ["Sci-Fi & Fantasy", "Drama"], "backdrop": "dGOhplPZTL0SKyb0ocTFBHIuKUC.jpg", "logo": "https://image.tmdb.org/t/p/w500/dGOhplPZTL0SKyb0ocTFBHIuKUC.jpg"}, {"title": "The Fabelmans", "language": "EN", "votes": "7.8", "date": "2022-11-11", "media_type": "Movie", "genre": ["Drama", "Comedy"], "backdrop": "6RCf9jzKxyjblYV4CseayK6bcJo.jpg", "logo": "https://image.tmdb.org/t/p/w500/6RCf9jzKxyjblYV4CseayK6bcJo.jpg"}, {"title": "The Seven Deadly Sins: Grudge of Edinburgh Part 1", "language": "JA", "votes": "7.8", "date": "2022-12-20", "media_type": "Movie", "genre": ["Animation", "Fantasy", "Adventure", "Action"], "backdrop": "24fe6ou97ammOg3O6ShCgaiolp4.jpg", "logo": "https://image.tmdb.org/t/p/w500/24fe6ou97ammOg3O6ShCgaiolp4.jpg"}, {"title": "Mindcage", "language": "EN", "votes": "7.6", "date": "2022-12-16", "media_type": "Movie", "genre": ["Mystery", "Thriller", "Crime", "Drama"], "backdrop": "An2M2gm0p8POaiGTcZvP1JnUItH.jpg", "logo": "https://image.tmdb.org/t/p/w500/An2M2gm0p8POaiGTcZvP1JnUItH.jpg"}, {"title": "Private Lesson", "language": "TR", "votes": "7.3", "date": "2022-12-16", "media_type": "Movie", "genre": ["Comedy", "Romance"], "backdrop": "uZtYhcnk3WWvUzQkJLqnNywMQpb.jpg", "logo": "https://image.tmdb.org/t/p/w500/uZtYhcnk3WWvUzQkJLqnNywMQpb.jpg"}, {"title": "Sonic Prime", "language": "EN", "votes": "8.7", "date": "2022-12-15", "media_type": "Tv", "genre": ["Animation", "Family"], "backdrop": "1Iiz2uLcZuLn4Khog2yiKpbl11.jpg", "logo": "https://image.tmdb.org/t/p/w500/1Iiz2uLcZuLn4Khog2yiKpbl11.jpg"}, {"title": "The Big 4", "language": "ID", "votes": "7.0", "date": "2022-12-19", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime"], "backdrop": "clO1mWRYT24ogzN3o6LsqHjqrQu.jpg", "logo": "https://image.tmdb.org/t/p/w500/clO1mWRYT24ogzN3o6LsqHjqrQu.jpg"}]}' >> movie_settings.json +echo '{"feature": "IPO", "speed": "medium", "speed2": "medium", "animation": "down", "title": true, "symbols": ["No Data"]}' >> ipo_settings.json +echo '{"symbols": {}}' >> portfolio_settings.json +echo '{"symbols": {}}' >> portfolio_crypto_settings.json +echo '{}' >> prepost_settings.json +echo '{"shutdown": {"hour": "00", "minute": "00", "enabled": false}, "reboot":{"hour": "00", "minute": "00", "enabled": false}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}}' >> scheduler.json echo '{"brightness": 10, "country_code": "GB", "hostname": "fintic"}' >> general_settings.json chmod 777 * @@ -95,6 +100,8 @@ touch 'Indices.ppm' touch 'Indices Prof.ppm' touch 'Movies.ppm' touch 'Movies Prof.ppm' +touch 'IPO Calendar.ppm' +touch 'IPO Calendar Prof.ppm' chmod 777 * diff --git a/static/app.js b/static/app.js index 02ffd8b..86a35d2 100755 --- a/static/app.js +++ b/static/app.js @@ -47,6 +47,7 @@ var messagesFeatures = document.querySelectorAll("#messages-features li"); var commoditiesFeatures = document.querySelectorAll("#commodities-features li"); var indicesFeatures = document.querySelectorAll("#indices-features li"); var moviesFeatures = document.querySelectorAll("#movies-features li"); +var ipoFeatures = document.querySelectorAll("#ipo-features li"); var allFeaturesList = [ stocksFeatures, @@ -65,6 +66,7 @@ var allFeaturesList = [ commoditiesFeatures, indicesFeatures, moviesFeatures, + ipoFeatures, ]; // features remove buttons @@ -90,6 +92,7 @@ var messagesRemoveBtn = document.getElementById("messages-remove-btn"); var commoditiesRemoveBtn = document.getElementById("commodities-remove-btn"); var indicesRemoveBtn = document.getElementById("indices-remove-btn"); var moviesRemoveBtn = document.getElementById("movies-remove-btn"); +var ipoRemoveBtn = document.getElementById("ipo-remove-btn"); var allFeaturesRemoveBtns = [ stocksRemoveBtn, @@ -108,6 +111,7 @@ var allFeaturesRemoveBtns = [ commoditiesRemoveBtn, indicesRemoveBtn, moviesRemoveBtn, + ipoRemoveBtn, ]; // features increase buttons var stocksincreaseBtn = document.getElementById("stocks-increase-btn"); @@ -132,6 +136,7 @@ var messagesincreaseBtn = document.getElementById("messages-increase-btn"); var commoditiesincreaseBtn = document.getElementById("commodities-increase-btn"); var indicesincreaseBtn = document.getElementById("indices-increase-btn"); var moviesincreaseBtn = document.getElementById("movies-increase-btn"); +var ipoincreaseBtn = document.getElementById("ipo-increase-btn"); var allFeaturesIncreaseBtns = [ stocksincreaseBtn, @@ -150,6 +155,7 @@ var allFeaturesIncreaseBtns = [ commoditiesincreaseBtn, indicesincreaseBtn, moviesincreaseBtn, + ipoincreaseBtn, ]; // features decrease buttons @@ -175,6 +181,7 @@ var messagesDecreaseBtn = document.getElementById("messages-decrease-btn"); var commoditiesDecreaseBtn = document.getElementById("commodities-decrease-btn"); var indicesDecreaseBtn = document.getElementById("indices-decrease-btn"); var moviesDecreaseBtn = document.getElementById("movies-decrease-btn"); +var ipoDecreaseBtn = document.getElementById("ipo-decrease-btn"); var allFeaturesDecreaseBtns = [ stocksDecreaseBtn, @@ -193,6 +200,7 @@ var allFeaturesDecreaseBtns = [ commoditiesDecreaseBtn, indicesDecreaseBtn, moviesDecreaseBtn, + ipoDecreaseBtn, ]; const changeVarValue = () => { @@ -218,7 +226,8 @@ const changeVarValue = () => { commoditiesFeatures = document.querySelectorAll("#commodities-features li"); indicesFeatures = document.querySelectorAll("#indices-features li"); moviesFeatures = document.querySelectorAll("#movies-features li"); - + ipoFeatures = document.querySelectorAll("#ipo-features li"); + allFeaturesList = [ stocksFeatures, cryptoFeatures, @@ -236,6 +245,7 @@ const changeVarValue = () => { commoditiesFeatures, indicesFeatures, moviesFeatures, + ipoFeatures, ]; }; @@ -515,38 +525,30 @@ allFeaturesRemoveBtns.map((value, index) => { for (let i = 0; i < allFeaturesList[index].length; i++) { var item = allFeaturesList[index][i]; console.log(item); - if (item.getAttribute("class") == "active") { - /* - if (item.parentElement.getAttribute("id") == "images-features") { - let getImages = JSON.parse(localStorage.getItem("customImages")); - - let filter = getImages.filter( - (value) => value.fileName !== item.innerText - ); - localStorage.setItem("customImages", JSON.stringify(filter)); - } else if (item.parentElement.getAttribute("id") == "gifs-features") { - let getGifs = JSON.parse(localStorage.getItem("customGifs")); - - let filter = getGifs.filter( - (value) => value.fileName !== item.innerText - ); - localStorage.setItem("customGifs", JSON.stringify(filter)); - } else if ( - item.parentElement.getAttribute("id") == "messages-features" - ) { - let getMsgs = JSON.parse(localStorage.getItem("customMsg")); - - let filter = getMsgs.filter( - (value) => value.messageName !== item.innerText - ); - localStorage.setItem("customMsg", JSON.stringify(filter)); - } - else { - */ + if ((item.getAttribute("class") == "active") && (index == 0 )){ + let symbol = item.innerText; + item.remove(); + uploaded_images = []; + uploaded_GIFs = []; + fetch("/deletePortfolioSettings", { + method: "POST", + body: JSON.stringify(symbol), + }); + } + else if ((item.getAttribute("class") == "active") && (index == 1 )){ + let symbol = item.innerText; + item.remove(); + uploaded_images = []; + uploaded_GIFs = []; + fetch("/deletePortfolioCryptoSettings", { + method: "POST", + body: JSON.stringify(symbol), + }); + } + else if (item.getAttribute("class") == "active") { item.remove(); uploaded_images = []; uploaded_GIFs = []; - //} } } }); @@ -607,6 +609,7 @@ var messages = document.getElementById("messages-features"); var commodities = document.getElementById("commodities-features"); var indices = document.getElementById("indices-features"); var movies = document.getElementById("movies-features"); +var ipos = document.getElementById("ipo-features"); var allFeatures = [ stocks, @@ -625,6 +628,7 @@ var allFeatures = [ commodities, indices, movies, + ipos, ]; // features select box @@ -651,6 +655,7 @@ var allFeaturesSelectBox = [ null, null, moviesSelect, + null, ]; // features select add buttons @@ -676,6 +681,7 @@ var allFeaturesSelectAddBtn = [ null, null, null, + null, ]; allFeaturesSelectAddBtn.map((value, index) => { @@ -711,6 +717,7 @@ var allFeaturesFile = [ null, null, null, + null, ]; // features file add button var imagesFileAddBtn = document.getElementById("inputTextBtn11"); @@ -733,6 +740,7 @@ var allFeaturesFileAddBtn = [ null, null, null, + null, ]; // features input text @@ -762,6 +770,7 @@ var allFeaturesText = [ commoditiesText, indicesText, null, + null, ]; // features text add button @@ -791,6 +800,7 @@ var allFeaturesTextAddBtn = [ commoditiesTextAddBtn, indicesTextAddBtn, null, + null, ]; @@ -811,6 +821,7 @@ var allFeaturesLimit = [ 30, 40, null, + null, ]; @@ -1071,6 +1082,7 @@ function getFeatureSettings() { "Commodities", "Indices", "Movies", + "IPO Calendar", ]; let pageNum = features.indexOf(feature) + 1; let pageSelector = "Page" + pageNum.toString(); @@ -1130,6 +1142,9 @@ function getFeatureSettings() { case 16: s = getMovieSettings(page); break; + case 17: + s = getIpoSettings(page); + break; } settings = { ...settings, ...s }; // merge both sets of settings @@ -1185,21 +1200,48 @@ let saveSettingsButtons = document.querySelectorAll(".save-btn").forEach((button // gets the stock, crypto or forex specific settings function getTradingSettings(page) { // get all the tick boxes + let whatFeature = document.getElementById('drop').value; let percent = page.querySelectorAll(".percent-select")[0].checked; let point = page.querySelectorAll(".point-select")[0].checked; let no_logos = page.querySelectorAll(".logo-select")[0].checked; let title = page.querySelectorAll(".title-select")[0].checked; - let symbols_el = page.querySelectorAll(".symbol-list")[0]; let symbols = getListItems(symbols_el); - let settings = { - percent: percent, - point: point, - logos: no_logos, - title: title, - symbols: symbols, - }; + if (whatFeature == 2) { + let portfolio = page.querySelectorAll(".portfolio-select")[0].checked; + settings = { + percent: percent, + point: point, + logos: no_logos, + title: title, + symbols: symbols, + chart: portfolio, + }; + } + else if (whatFeature == 1) { + let prepost = page.querySelectorAll(".prepost-select")[0].checked; + let portfolio = page.querySelectorAll(".portfolio-select")[0].checked; + settings = { + prepost: prepost, + percent: percent, + point: point, + logos: no_logos, + title: title, + symbols: symbols, + chart: portfolio, + }; + } + else { + settings = { + percent: percent, + point: point, + logos: no_logos, + title: title, + symbols: symbols, + }; + } + console.log(settings); return settings; } @@ -1254,6 +1296,7 @@ function saveWeatherAPIKey(){ "Commodities", "Indices", "Movies", + "IPO Calendar", ]; let pageNum = features.indexOf(feature) + 1; let pageSelector = "Page" + pageNum.toString(); @@ -1294,6 +1337,7 @@ function saveMovieAPIKey(){ "Commodities", "Indices", "Movies", + "IPO Calendar", ]; let pageNum = features.indexOf(feature) + 1; let pageSelector = "Page" + pageNum.toString(); @@ -1314,6 +1358,49 @@ function saveMovieAPIKey(){ } +function saveIpoAPIKey(){ + let featureSelector = document.getElementById("drop"); + feature = getSelected(featureSelector); + let features = [ + "Stocks", + "Crypto", + "Forex", + "Current Weather", + "Daily Forecast", + "News", + "Sports (Upcoming Games)", + "Sports (Past Games)", + "Sports (Live Games)", + "Sports (Team Stats)", + "Custom Images", + "Custom GIFs", + "Custom Messages", + "Commodities", + "Indices", + "Movies", + "IPO Calendar", + ]; + let pageNum = features.indexOf(feature) + 1; + let pageSelector = "Page" + pageNum.toString(); + + let page = document.getElementById(pageSelector); + + let api_key = page.querySelectorAll(".api-key")[0].value; + let settings = { + api_key:api_key + }; + + console.log(settings); + + fetch("/saveIpoAPIKey", { + method: "POST", + body: JSON.stringify(settings), + }); +} + +var ipoAPIbtn = document.getElementById("ipo-api-btn"); +ipoAPIbtn.addEventListener("click", saveIpoAPIKey); + var movieAPIbtn = document.getElementById("movie-api-btn"); movieAPIbtn.addEventListener("click", saveMovieAPIKey); @@ -1358,6 +1445,18 @@ function getMovieSettings(page) { return settings; } + +function getIpoSettings(page) { + let title = page.querySelectorAll(".title-select")[0].checked; + let api_key = page.querySelectorAll(".api-key")[0]; + + settings = { + title: title, + api_key: api_key + }; + return settings; +} + function getSportsSettings(page) { let title = page.querySelectorAll(".title-select")[0].checked; let leagues_el = page.querySelectorAll(".league-list")[0]; @@ -1661,7 +1760,7 @@ inputAnimationBtn.addEventListener("click", () => { // scroll speed row two let inputScrollSpeedRow = []; -for (let i = 1; i <= 16; i++) { +for (let i = 1; i <= 17; i++) { inputScrollSpeedRow.push( document.getElementById( i === 1 ? "inputScrollSpeedRow" : `inputScrollSpeedRow${i}` @@ -1818,6 +1917,25 @@ function showMovieP() { } + +function showIpoP() { + if(document.getElementById("api-key-ipo").value==="") { + + document.getElementById('ipo-api-p').style.display = "none"; + } + + else if (document.getElementById("api-key-ipo").value==="IPO Calendar API Key") { + document.getElementById('ipo-api-p').style.display = "none"; + + } + + else { + document.getElementById('ipo-api-p').style.display = "block" + } + + } + + // Disable adding cities when no API key detected @@ -1856,7 +1974,13 @@ function stockValidate() { var specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,<>\/?~]/; let x = document.getElementById("inputText3").value; + let portfolioCheckbox = document.getElementById("flexCheckChecked4"); + let sharesText = document.getElementById("inputText8").value; + let averageCost = document.getElementById("inputText9").value; + let dateText = document.getElementById("inputText10").value; + let text; + let text2; if (x.toUpperCase() != x) { document.getElementById('demo').style.display = "block"; text = "Stock symbol must be uppercase"; @@ -1868,23 +1992,19 @@ var specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,<>\/?~]/; document.getElementById('demo').style.display = "block"; text = "No blanks" // createLi = false; - } - else if (x.includes(' ')) { text = "No spaces"; document.getElementById('demo').style.display = "block"; document.getElementById("inputText3").value = ''; // createLi = false; } - else if (x.length > 5) { document.getElementById('demo').style.display = "block"; text = "No more than 5 characters"; document.getElementById("inputText3").value = ''; // createLi = false; } - else if (/\d/.test(x)) { document.getElementById('demo').style.display = "block"; text = "No numbers allowed"; @@ -1892,24 +2012,96 @@ var specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,<>\/?~]/; // createLi = false; } // CAREFUL TO DELETE THE BACKEND LIST ITEMS, JUST DELETING THE VALUE LIKE THIS ISN"T 100% ACCURATE - else if (specialChars.test(x)) { document.getElementById('demo').style.display = "block"; text = "No special characters allowed"; document.getElementById("inputText3").value = ''; // createLi = false; } - else { text = "Input OK"; document.getElementById('demo').style.display = "none"; - createLi = true; - // CALL ADDING ITEMS FUNCTION SO THAT ONLY VALIDATED ITEMS CAN GET ADDED TO LIST - // addingItems(); - setTimeout( - function() { - document.getElementById('inputText3').value=""; - }, 100); + //PORTFOLIO VALIDATION HERE + if (portfolioCheckbox.checked) { + if ((sharesText === ' ') || (averageCost === ' ') || (dateText === ' ')) { + text2 = "No spaces"; + document.getElementById('demo-portfolio').style.display = "block"; + document.getElementById("inputText8").value = ''; + document.getElementById("inputText9").value = ''; + document.getElementById("inputText10").value = ''; + document.getElementById("inputText3").value = ''; + } + else if ((isNaN(sharesText))|| (isNaN(averageCost))) { + text2 = "No text characters, only numbers"; + document.getElementById('demo-portfolio').style.display = "block"; + document.getElementById("inputText8").value = ''; + document.getElementById("inputText9").value = ''; + document.getElementById("inputText10").value = ''; + document.getElementById("inputText3").value = ''; + } + else if ((!dateText.includes('-')) && (dateText !== '')) { + text2 = "Incorrect date format, it should be YYYY-MM-DD"; + document.getElementById('demo-portfolio').style.display = "block"; + document.getElementById("inputText8").value = ''; + document.getElementById("inputText9").value = ''; + document.getElementById("inputText10").value = ''; + document.getElementById("inputText3").value = ''; + } + else if (((sharesText !== '') || (averageCost !== '') || (dateText !== '')) && ((sharesText === '') || (averageCost === '') || (dateText === ''))) { + text2 = "Some fields are empty"; + document.getElementById('demo-portfolio').style.display = "block"; + document.getElementById("inputText8").value = ''; + document.getElementById("inputText9").value = ''; + document.getElementById("inputText10").value = ''; + document.getElementById("inputText3").value = ''; + } + else { + text2 = "Input OK"; + document.getElementById('demo-portfolio').style.display = "none"; + createLi = true; + // CALL ADDING ITEMS FUNCTION SO THAT ONLY VALIDATED ITEMS CAN GET ADDED TO LIST + // addingItems(); + let cost = document.getElementById('inputText9').value; + let shares = document.getElementById('inputText8').value; + let symbol = document.getElementById('inputText3').value; + let days = document.getElementById('inputText10').value; + + let settings = { + shares:shares, + cost:cost, + symbol:symbol, + days:days, + }; + console.log(JSON.stringify(settings)); + + setTimeout( + function() { + document.getElementById('inputText3').value=""; + document.getElementById("inputText8").value = ''; + document.getElementById("inputText9").value = ''; + document.getElementById("inputText10").value = ''; + document.getElementById("inputText3").value = ''; + }, 100); + + if ((sharesText !== '') && (averageCost !== '') && (dateText !== '')) { + fetch("/savePortfolioSettings", { + method: "POST", + body: JSON.stringify(settings), + }); + } + } + document.getElementById("demo-portfolio").innerHTML = text2; + } + + else { + createLi = true; + // CALL ADDING ITEMS FUNCTION SO THAT ONLY VALIDATED ITEMS CAN GET ADDED TO LIST + // addingItems(); + setTimeout( + function() { + document.getElementById('inputText3').value=""; + }, 100); + } } document.getElementById("demo").innerHTML = text; } @@ -1923,10 +2115,13 @@ var specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|<>\/?~]/; let x = document.getElementById("inputText4").value; let baseCurrency = x.split(",")[1]; - - // console.log(baseCurrency) + let portfolioCheckbox = document.getElementById("crypto_portfolio_checkbox"); + let sharesText = document.getElementById("cryptoshares").value; + let averageCost = document.getElementById("cryptocost").value; + let dateText = document.getElementById("cryptodate").value; let text; + let text2; if (x.toUpperCase() != x) { document.getElementById('demo2').style.display = "block"; text = "Crypto and base must be uppercase"; @@ -1938,21 +2133,18 @@ var specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|<>\/?~]/; text = "No blanks" // createLi = false; } - else if (x.includes(' ')) { text = "No spaces"; document.getElementById('demo2').style.display = "block"; document.getElementById("inputText4").value = ''; // createLi = false; } - else if (specialChars.test(x)) { document.getElementById('demo2').style.display = "block"; text = "No special characters allowed"; document.getElementById("inputText4").value = ''; // createLi = false; } - else if (!x.includes(',')) { document.getElementById('demo2').style.display = "block"; document.getElementById("inputText4").value = ''; @@ -1970,12 +2162,85 @@ var specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|<>\/?~]/; else { text = "Input OK"; document.getElementById('demo2').style.display = "none"; - createLi = true; - // CALL ADDING ITEMS FUNCTION SO THAT ONLY VALIDATED ITEMS CAN GET ADDED TO LIST - setTimeout( - function() { - document.getElementById('inputText4').value=""; - }, 100); + //PORTFOLIO VALIDATION HERE + if (portfolioCheckbox.checked) { + if ((sharesText === ' ') || (averageCost === ' ') || (dateText === ' ')) { + text2 = "No spaces"; + document.getElementById('demo-portfolio-crypto').style.display = "block"; + document.getElementById("cryptoshares").value = ''; + document.getElementById("cryptocost").value = ''; + document.getElementById("cryptodate").value = ''; + document.getElementById("inputText4").value = ''; + } + else if ((isNaN(sharesText))|| (isNaN(averageCost))) { + text2 = "No text characters, only numbers"; + document.getElementById('demo-portfolio-crypto').style.display = "block"; + document.getElementById("cryptoshares").value = ''; + document.getElementById("cryptocost").value = ''; + document.getElementById("cryptodate").value = ''; + document.getElementById("inputText4").value = ''; + } + else if ((!dateText.includes('-')) && (dateText !== '')) { + text2 = "Incorrect date format, it should be YYYY-MM-DD"; + document.getElementById('demo-portfolio-crypto').style.display = "block"; + document.getElementById("cryptoshares").value = ''; + document.getElementById("cryptocost").value = ''; + document.getElementById("cryptodate").value = ''; + document.getElementById("inputText4").value = ''; + } + else if (((sharesText !== '') || (averageCost !== '') || (dateText !== '')) && ((sharesText === '') || (averageCost === '') || (dateText === ''))) { + text2 = "Some fields are empty"; + document.getElementById('demo-portfolio-crypto').style.display = "block"; + document.getElementById("cryptoshares").value = ''; + document.getElementById("cryptocost").value = ''; + document.getElementById("cryptodate").value = ''; + document.getElementById("inputText4").value = ''; + } + else { + text2 = "Input OK"; + document.getElementById('demo-portfolio-crypto').style.display = "none"; + createLi = true; + + let cost = document.getElementById('cryptocost').value; + let shares = document.getElementById('cryptoshares').value; + let symbol = document.getElementById('inputText4').value; + let days = document.getElementById('cryptodate').value; + + let settings = { + shares:shares, + cost:cost, + symbol:symbol, + days:days, + }; + console.log(JSON.stringify(settings)); + + setTimeout( + function() { + document.getElementById('inputText4').value=""; + document.getElementById("cryptocost").value = ''; + document.getElementById("cryptoshares").value = ''; + document.getElementById("cryptodate").value = ''; + document.getElementById("inputText4").value = ''; + }, 100); + + if ((sharesText !== '') && (averageCost !== '') && (dateText !== '')) { + fetch("/savePortfolioCryptoSettings", { + method: "POST", + body: JSON.stringify(settings), + }); + } + } + document.getElementById("demo-portfolio-crypto").innerHTML = text2; + } + + else { + createLi = true; + // CALL ADDING ITEMS FUNCTION SO THAT ONLY VALIDATED ITEMS CAN GET ADDED TO LIST + setTimeout( + function() { + document.getElementById('inputText4').value=""; + }, 100); + } } document.getElementById("demo2").innerHTML = text; } @@ -2231,7 +2496,7 @@ var specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|<>\/?~]/; } else if (!["ALU","BRENTOIL","LCO","COFFEE","XCU","CORN","COTTON","XAU","IRD","NI","XPD","XPT","XRH","RICE","RUTH","XAG","SOYBEAN", - "XDR","SUGAR","TIN","WHEAT","WTIOIL","ZNC","ETHANOL","CPO","NG","COCOA","ROBUSTA","LUMBER","RUBBER"].includes(x)) { + "XDR","SUGAR","TIN","WHEAT","WTIOIL","ZNC","ETHANOL","CPO","NG","COCOA","ROBUSTA","LUMBER","RUBBER","HOG","CATTLE"].includes(x)) { document.getElementById('demo8').style.display = "block"; document.getElementById("inputText20").value = ''; text = "Invalid commodity symbol" @@ -2307,3 +2572,126 @@ var specialChars = /[`!@#$%&*()_+\-=\[\]{};':"\\|<>\/?~]/; } document.getElementById("demo9").innerHTML = text; } + + +// portoflio stuff + + var portfolioCheckbox = document.getElementById("flexCheckChecked4"); + if (portfolioCheckbox.checked) { + document.getElementById('stocks-portfolio').style.display = "block"; + } else { + document.getElementById('stocks-portfolio').style.display = "none"; + } + + +function portfolioValidate() { + var portfolioCheckbox = document.getElementById("flexCheckChecked4"); + if (portfolioCheckbox.checked) { + document.getElementById('stocks-portfolio').style.display = "block"; + } else { + document.getElementById('stocks-portfolio').style.display = "none"; + } +} + + +// crypto portfolio stuff + +var portfolioCryptoCheckbox = document.getElementById("crypto_portfolio_checkbox"); +if (portfolioCryptoCheckbox.checked) { + document.getElementById('crypto-portfolio').style.display = "block"; +} else { + document.getElementById('crypto-portfolio').style.display = "none"; +} + + +function portfolioCryptoValidate() { + var portfolioCryptoCheckbox = document.getElementById("crypto_portfolio_checkbox"); + if (portfolioCryptoCheckbox.checked) { + document.getElementById('crypto-portfolio').style.display = "block"; + } else { + document.getElementById('crypto-portfolio').style.display = "none"; + } +} + + + + + +// scheduler show div + +function showScheduler() { + document.getElementById('scheduler-div').style.display = "block"; +} + +function closeScheduler() { + document.getElementById('scheduler-div').style.display = "none"; + document.getElementById('saved').style.display = "none"; +} + +// save scheduler settings + +function saveSchedulerSettings() { + let shutdown_hour = document.getElementById("shutdown-hour-select").value; + let shutdown_minute = document.getElementById("shutdown-minute-select").value; + let shutdown_enabled = document.getElementById("shutdown-enabled").checked; + + let reboot_hour = document.getElementById("reboot-hour-select").value; + let reboot_minute = document.getElementById("reboot-minute-select").value; + let reboot_enabled = document.getElementById("reboot-enabled").checked; + + let brightness1_hour = document.getElementById("brightness1-hour1-select").value; + let brightness1_minute = document.getElementById("brightness1-minute1-select").value; + let brightness1_enabled = document.getElementById("brightness1-enabled").checked; + let brightness1_bright = document.getElementById("brightness1-bright-select").value; + + let brightness2_hour = document.getElementById("brightness2-hour1-select").value; + let brightness2_minute = document.getElementById("brightness2-minute1-select").value; + let brightness2_enabled = document.getElementById("brightness2-enabled").checked; + let brightness2_bright = document.getElementById("brightness2-bright-select").value; + + let brightness3_hour = document.getElementById("brightness3-hour1-select").value; + let brightness3_minute = document.getElementById("brightness3-minute1-select").value; + let brightness3_enabled = document.getElementById("brightness3-enabled").checked; + let brightness3_bright = document.getElementById("brightness3-bright-select").value; + + let brightness4_hour = document.getElementById("brightness4-hour1-select").value; + let brightness4_minute = document.getElementById("brightness4-minute1-select").value; + let brightness4_enabled = document.getElementById("brightness4-enabled").checked; + let brightness4_bright = document.getElementById("brightness4-bright-select").value; + + let timezone = document.getElementById("timezone-select").value; + + let settings = { + shutdown_hour: shutdown_hour, + shutdown_minute: shutdown_minute, + shutdown_enabled: shutdown_enabled, + reboot_hour: reboot_hour, + reboot_minute: reboot_minute, + reboot_enabled: reboot_enabled, + timezone: timezone, + brightness1_hour: brightness1_hour, + brightness1_minute: brightness1_minute, + brightness1_bright: brightness1_bright, + brightness1_enabled: brightness1_enabled, + brightness2_hour: brightness2_hour, + brightness2_minute: brightness2_minute, + brightness2_bright: brightness2_bright, + brightness2_enabled: brightness2_enabled, + brightness3_hour: brightness3_hour, + brightness3_minute: brightness3_minute, + brightness3_bright: brightness3_bright, + brightness3_enabled: brightness3_enabled, + brightness4_hour: brightness4_hour, + brightness4_minute: brightness4_minute, + brightness4_bright: brightness4_bright, + brightness4_enabled: brightness4_enabled, + }; + + console.log(settings); + fetch("/saveSchedulerSettings", { + method: "POST", + body: JSON.stringify(settings), + }); + document.getElementById('saved').style.display = "block"; +} + diff --git a/static/style.css b/static/style.css index e4fbfe4..eb361f5 100755 --- a/static/style.css +++ b/static/style.css @@ -1121,6 +1121,10 @@ h3 { color:red; } +#ipo-api-p { + color:red; +} + label:hover { cursor:text; } @@ -1165,6 +1169,141 @@ input[type=checkbox]:hover { color:red; } +#demo-portfolio { + color:red; +} + +#demo-portfolio-crypto { + color:red; +} + #limit-msg { color:red; } + + + + +#scheduler-div { + width: 480px; + height: 430px; + border-radius:20px; +/* background-color: #282828;*/ + background-color: rgba(5,5,5,0.7); + backdrop-filter: blur(6px); + border-color: #5D5D5D; + border-style: solid; + border-width: thin; + + position: fixed; /*Can also be `fixed`*/ + left: 0; + right: 0; + top: 0; + bottom: 0; + margin: auto; + /*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/ + max-width: 100%; + max-height: 100%; + overflow: auto; + z-index:98; +} + +#scheduler-close-btn { + background-color: transparent; + border: none; + color: white; + text-decoration: underline; + margin-left:42%; + +} + +#scheduler-close-btn:hover { + background-color: transparent; + border: none; + color: darkgray; + text-decoration: underline; +} + +#scheduler-close-btn:active { + background-color: transparent; + border: none; + color: #4B4B4B; + text-decoration: underline; +} + +#scheduler-p { + font-size:20px; + display: inline; +} + +#scheduler-top { + margin-top:3%; + padding: 5%; + padding-top: 1%; +} + +.hour-select { + width:22%; + display: inline; + margin-right: 2%; +} + +.scheduler-hour-select { + display: inline; + zoom:1.2; +} + +.minute-select { + width:22%; + display: inline; + margin-right: 2%; +} + +.timezone-select { + width:50%; + display: inline; +} + +#shutdowns-p { + margin-top: 5%; + margin-bottom: 2%; +} + +#reboots-p { + margin-top:6%; + margin-bottom:2%; +} + +#inside-scheduler-div { + margin-left: 5%; +} + + +.btn-scheduler { + background-color: #003337; + border-color:#00CFDF; + color:white; +} + +.btn-scheduler:hover { + color:white; + background-color:#008993; + border-color:#00EDFF; +} + +.btn-scheduler:active { + color:grey; + background-color:#002225; + border-color:#00CFDF; +} + +.b-minute-select { + width:17%; + display: inline; +} + +#brightness-p { + margin-top:6%; + margin-bottom:2%; +} + diff --git a/stockTicker.py b/stockTicker.py index 624c23e..2fe798f 100755 --- a/stockTicker.py +++ b/stockTicker.py @@ -25,6 +25,8 @@ import json from datetime import datetime import matplotlib.colors as mcolors +ny_zone = pytz.timezone('America/New_York') + def getInput(Block=False): if Block or select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): msg = sys.stdin.read(1) @@ -69,7 +71,7 @@ class StockTicker(): 'Sports (Team Stats)':lambda : self.getLeagueTableImage('premier_league'), 'Sports (Past Games)': lambda:self.getLeagueImage('NBA', 'past'), 'Sports (Upcoming Games)': lambda : self.getLeagueImage('NHL', 'future'), 'Sports (Live Games)': lambda: self.getLeagueImage('NBA', 'live'), 'News':self.getNewsImage, 'Custom Messages': self.getUserMessages, 'Commodities': self.getCommoditiesImage, 'Indices': self.getIndicesImage, 'Movies': self.getMoviesImage, - + 'IPO Calendar':self.getIpoImage, 'IPO Calendar Prof':self.getIpoProfessional, 'Stocks Prof': self.getStockProfessional, 'Crypto Prof': self.getCryptoProfessional, 'Forex Prof': self.getForexProfessional, 'Current Weather Prof': self.getTodayWeatherProfessional, 'News Prof':self.getNewsProfessional, 'Commodities Prof':self.getCommoditiesProfessional, 'Indices Prof': self.getIndicesProfessional, @@ -78,12 +80,12 @@ class StockTicker(): self.JSONs = {'Stocks': 'csv/stocks_settings.json', 'Crypto': 'csv/crypto_settings.json', 'Forex': 'csv/forex_settings.json', 'Daily Forecast':'csv/daily_weather.json', 'Current Weather': 'csv/current_weather.json', 'Commodities':'csv/commodities_settings.json', 'Indices': 'csv/indices_settings.json', - 'Sports (Team Stats)': 'csv/league_tables.json', 'Sports (Past Games)': 'csv/past_games.json', + 'Sports (Team Stats)': 'csv/league_tables.json', 'Sports (Past Games)': 'csv/past_games.json', 'IPO Calendar': 'csv/ipo_settings.json', 'Sports (Upcoming Games)': 'csv/upcoming_games.json', 'Sports (Live Games)': 'csv/live_games.json', 'Movies': 'csv/movie_settings.json', 'News':'csv/news_settings.json', 'Custom Images': 'csv/image_settings.json', 'Custom GIFs': 'csv/GIF_settings.json', 'Custom Messages': 'csv/message_settings.json', 'Stocks Prof': 'csv/stocks_settings.json', 'Crypto Prof': 'csv/crypto_settings.json', 'Forex Prof': 'csv/forex_settings.json', 'Current Weather Prof': 'csv/current_weather.json', 'News Prof':'csv/news_settings.json', 'Commodities Prof':'csv/commodities_settings.json', 'Indices Prof': 'csv/indices_settings.json', - 'Daily Forecast Prof':'csv/daily_weather.json', 'Sports (Team Stats) Prof': 'csv/league_tables.json', 'Sports (Upcoming Games) Prof': 'csv/upcoming_games.json', 'Sports (Past Games) Prof': 'csv/past_games.json', 'Custom Messages Prof': 'csv/message_settings.json', 'Custom Images Prof': 'csv/image_settings.json', 'Movies Prof': 'csv/movie_settings.json', 'Sports (Live Games) Prof': 'csv/live_games.json'} + 'Daily Forecast Prof':'csv/daily_weather.json', 'Sports (Team Stats) Prof': 'csv/league_tables.json', 'Sports (Upcoming Games) Prof': 'csv/upcoming_games.json', 'Sports (Past Games) Prof': 'csv/past_games.json', 'Custom Messages Prof': 'csv/message_settings.json', 'Custom Images Prof': 'csv/image_settings.json', 'Movies Prof': 'csv/movie_settings.json', 'Sports (Live Games) Prof': 'csv/live_games.json', 'IPO Calendar Prof': 'csv/ipo_settings.json'} def openImage(self, image_file): @@ -703,15 +705,10 @@ class StockTicker(): #displays the text entered in the webpage by the user. - - - f = open('csv/message_settings.json', 'r') all_settings = json.load(f) f.close() - - - + colours = {'Black':(0,0,0), 'White':(255,255,255), 'Red':(255,0,0), @@ -736,14 +733,14 @@ class StockTicker(): elif message["size"] == 'Small': font = ImageFont.load("./fonts/6x13.pil") location = (0, 7) - - + r,g,b = colours[message['text_colour']] background = colours[message['background_colour']] + decoded = message['text'].encode("ascii","ignore") + message['text'] = decoded.decode() img = self.textImage(message['text'], font, int(r), int(g), int(b), True, w_buff = 5, background = background, location = location) - - + if all_settings['title'] and ind == 0: title_img = self.openImage('feature_titles/message.png') imgs.append(self.stitchImage([title_img, img])) @@ -792,6 +789,8 @@ class StockTicker(): r,g,b = colours[message['text_colour']] background = colours[message['background_colour']] + decoded = message['text'].encode("ascii","ignore") + message['text'] = decoded.decode() msg_img = self.textImage(message['text'], font, int(r), int(g), int(b), True, w_buff = 11, background = background, location = location) img = Image.new('RGB', (msg_img.size[0] + 5, 32)) @@ -808,6 +807,8 @@ class StockTicker(): r,g,b = colours[message['text_colour']] background = colours[message['background_colour']] + decoded = message['text'].encode("ascii","ignore") + message['text'] = decoded.decode() msg_img = self.textImage(message['text'], font, int(r), int(g), int(b), True, w_buff = 11, background = background, location = location) img = Image.new('RGB', (msg_img.size[0] + 130, 32)) @@ -987,7 +988,6 @@ class StockTicker(): def getCryptoImage(self): - f = open('csv/crypto_settings.json', 'r') all_crypto_settings = json.load(f) f.close() @@ -999,7 +999,13 @@ class StockTicker(): else: image_list = [] - + if all_crypto_settings['chart']: + try: + f = open('csv/portfolio_crypto_settings.json', 'r') + portfolio_settings = json.load(f)['symbols'] + f.close() + except: + pass coin_info = all_crypto_settings['symbols'] coin_bases = list(coin_info.keys()) @@ -1019,8 +1025,17 @@ class StockTicker(): arrow, change = self.getArrow(point_change) percent_change = '%.2f' % abs(percent_change) + '%' - point_change = str(point_changefinal) - current = str(current_final) + num3 = point_changefinal.split('.') + if len(num3[1]) <= 1: + point_change = '%.2f' % float(point_changefinal) + else: + point_change = str(point_changefinal) + + num2 = current_final.split('.') + if len(num2[1]) <= 1: + current = '%.2f' % float(current_final) + else: + current = str(current_final) if not all_crypto_settings['percent']: percent_change = False @@ -1040,31 +1055,111 @@ class StockTicker(): stitchedStock = midFrame else: stitchedStock = midFrame - + + try: + if all_crypto_settings['chart'] and (cb in portfolio_settings): #IF USER INPUTTED PORTFOLIO SETTINGS, DISPLAY PORTFOLIO INFO + try: + cost = portfolio_settings[cb]['cost'] + day = portfolio_settings[cb]['day'] + shares = portfolio_settings[cb]['shares'] + + original_value = float(cost) * float(shares) + new_value = float(coin_info[cb]['current']) * float(shares) + value_day_change_percent = ((float(coin_info[cb]['percent_change'])/100) * new_value) + + font = ImageFont.load("./fonts/5x8.pil") + cost_img = self.textImage('Cost', font, r = 255, g = 255 , b = 255) + cost2_img = self.textImage(cost, font, r = 0, g = 255, b = 0) + shares_img = self.textImage('Shares', font, r = 255, g = 255 , b = 255) + shares2_img = self.textImage(shares, font, r = 0, g = 255, b = 0) + + pnlchange = new_value - original_value + pnlpercent = ((new_value - original_value) / original_value) * 100 + + pnlpercent_img = self.textImage('P/L%', font, r = 255, g = 255 , b = 255) + if pnlpercent >= 0: + pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 0, g = 255, b = 0) + else: + pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 255, g = 0, b = 0) + + + daypercent_img = self.textImage('Day%', font, r = 255, g = 255 , b = 255) + if float(coin_info[cb]['percent_change']) >= 0: + daypercent2_img = self.textImage(str('%.2f' % abs(float(coin_info[cb]['percent_change']))) +'%', font, r = 0, g = 255, b = 0) + else: + daypercent2_img = self.textImage(str('%.2f' % abs(float(coin_info[cb]['percent_change'])))+'%', font, r = 255, g = 0, b = 0) + + days_img = self.textImage('Days', font, r = 255, g = 255 , b = 255) + days2_img = self.textImage(day, font, r = 0, g = 255, b = 0) + value_img = self.textImage('Value', font, r = 255, g = 255 , b = 255) + value2_img = self.textImage(str('%.2f' % abs(original_value)), font, r = 0, g = 255, b = 0) + + pnlchange_img = self.textImage('P/L$', font, r = 255, g = 255 , b = 255) + if pnlchange >= 0: + pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 0, g = 255, b = 0) + else: + pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 255, g = 0, b = 0) + + daychange_img = self.textImage('Day$', font, r = 255, g = 255 , b = 255) + if value_day_change_percent >= 0: + daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 0, g = 255, b = 0) + else: + daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 255, g = 0, b = 0) + + x_offset = 0 + + img = Image.new('RGB', (max(cost_img.size[0], cost2_img.size[0], days_img.size[0], days2_img.size[0]) + 7 + + max(shares_img.size[0], shares2_img.size[0], value2_img.size[0], value_img.size[0]) + 7 + + max(pnlpercent_img.size[0], pnlpercent2_img.size[0], pnlchange_img.size[0], pnlchange2_img.size[0]) + 7 + + max(daypercent_img.size[0], daypercent2_img.size[0], daychange_img.size[0], daychange2_img.size[0]) + 15, 32)) + + img.paste(cost_img, (x_offset, 0)) + img.paste(cost2_img, (x_offset, 8)) + img.paste(days_img, (x_offset, 16)) + img.paste(days2_img, (x_offset, 24)) + x_offset += max(cost_img.size[0], cost2_img.size[0], days_img.size[0], days2_img.size[0]) + 7 + + img.paste(shares_img, (x_offset, 0)) + img.paste(shares2_img, (x_offset, 8)) + img.paste(value_img, (x_offset, 16)) + img.paste(value2_img, (x_offset, 24)) + x_offset += max(shares_img.size[0], shares2_img.size[0], value2_img.size[0], value_img.size[0]) + 7 + + img.paste(pnlpercent_img, (x_offset, 0)) + img.paste(pnlpercent2_img, (x_offset, 8)) + img.paste(pnlchange_img, (x_offset, 16)) + img.paste(pnlchange2_img, (x_offset, 24)) + x_offset += max(pnlpercent_img.size[0], pnlpercent2_img.size[0], pnlchange_img.size[0], pnlchange2_img.size[0]) + 7 + + img.paste(daypercent_img, (x_offset, 0)) + img.paste(daypercent2_img, (x_offset, 8)) + img.paste(daychange_img, (x_offset,16)) + img.paste(daychange2_img, (x_offset, 24)) + except: + pass + except: + pass + image_list.append(stitchedStock) - + try: + if all_crypto_settings['chart'] and (cb in portfolio_settings): + try: + image_list.append(img) + except: + pass + except: + pass image_list.append(self.blank) - except Exception as e: pass -# logf = open('log.txt', "a") -# exc_type, exc_obj, exc_tb = sys.exc_info() -# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] -# logf.write(str(e)) -# logf.write('. file: ' + fname) -# logf.write('. line: ' + str(exc_tb.tb_lineno)) -# logf.write('. type: ' + str(exc_type)) -# logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) -# logf.close() - finalDisplayImage = self.stitchImage(image_list) return finalDisplayImage + def getCryptoProfessional(self): - - + self.blank = Image.new('RGB', (0, 16)) f = open('csv/crypto_settings.json', 'r') @@ -1077,15 +1172,18 @@ class StockTicker(): image_list.append(self.blank) else: image_list = [] - - + + if all_crypto_settings['chart']: + try: + f = open('csv/portfolio_crypto_settings.json', 'r') + portfolio_settings = json.load(f)['symbols'] + f.close() + except: + pass coin_info = all_crypto_settings['symbols'] coin_bases = list(coin_info.keys()) - - - for i, cb in enumerate(coin_bases): try: ticker, base = cb.split(',') @@ -1100,10 +1198,18 @@ class StockTicker(): # convert percent to points change = '%.2f' % abs(float(coin_info[cb]['percent_change'])) + '%' else: - - change = str(changefinal) - - current = str(current_final) + num3 = changefinal.split('.') + if len(num3[1]) <= 1: + change = '%.2f' % float(changefinal) + else: + change = str(changefinal) + + num2 = current_final.split('.') + if len(num2[1]) <= 1: + current = '%.2f' % float(current_final) + else: + current = str(current_final) + midFrame = self.textToImageProf(ticker + '(' + base + ')', current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT if all_crypto_settings['logos']: try: @@ -1118,21 +1224,110 @@ class StockTicker(): stitchedStock = midFrame else: stitchedStock = midFrame + + try: + if all_crypto_settings['chart'] and (cb in portfolio_settings): #IF USER INPUTTED PORTFOLIO SETTINGS, DISPLAY PORTFOLIO INFO + try: + cost = portfolio_settings[cb]['cost'] + day = portfolio_settings[cb]['day'] + shares = portfolio_settings[cb]['shares'] + + original_value = float(cost) * float(shares) + new_value = float(coin_info[cb]['current']) * float(shares) + value_day_change_percent = ((float(coin_info[cb]['percent_change'])/100) * new_value) + + font = ImageFont.load("./fonts/5x8.pil") + cost_img = self.textImage('Cost', font, r = 255, g = 255 , b = 255) + cost2_img = self.textImage(cost, font, r = 0, g = 255, b = 0) + shares_img = self.textImage('Shares', font, r = 255, g = 255 , b = 255) + shares2_img = self.textImage(shares, font, r = 0, g = 255, b = 0) + + pnlchange = new_value - original_value + pnlpercent = ((new_value - original_value) / original_value) * 100 + + pnlpercent_img = self.textImage('P/L%', font, r = 255, g = 255 , b = 255) + if pnlpercent >= 0: + pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 0, g = 255, b = 0) + else: + pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 255, g = 0, b = 0) + + + daypercent_img = self.textImage('Day%', font, r = 255, g = 255 , b = 255) + if float(coin_info[cb]['percent_change']) >= 0: + daypercent2_img = self.textImage(str('%.2f' % abs(float(coin_info[cb]['percent_change']))) +'%', font, r = 0, g = 255, b = 0) + else: + daypercent2_img = self.textImage(str('%.2f' % abs(float(coin_info[cb]['percent_change'])))+'%', font, r = 255, g = 0, b = 0) + + days_img = self.textImage('Days', font, r = 255, g = 255 , b = 255) + days2_img = self.textImage(day, font, r = 0, g = 255, b = 0) + value_img = self.textImage('Value', font, r = 255, g = 255 , b = 255) + value2_img = self.textImage(str('%.2f' % abs(original_value)), font, r = 0, g = 255, b = 0) + + pnlchange_img = self.textImage('P/L$', font, r = 255, g = 255 , b = 255) + if pnlchange >= 0: + pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 0, g = 255, b = 0) + else: + pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 255, g = 0, b = 0) + + daychange_img = self.textImage('Day$', font, r = 255, g = 255 , b = 255) + if value_day_change_percent >= 0: + daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 0, g = 255, b = 0) + else: + daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 255, g = 0, b = 0) + + x_offset = 0 + + img = Image.new('RGB', (max(cost_img.size[0], cost2_img.size[0]) + 5 + max(days_img.size[0], days2_img.size[0]) + 5 + + max(shares_img.size[0], shares2_img.size[0]) + 5 + max(value2_img.size[0], value_img.size[0]) + 5 + + max(pnlpercent_img.size[0], pnlpercent2_img.size[0]) + 5 + max(pnlchange_img.size[0], pnlchange2_img.size[0]) + 5 + + max(daypercent_img.size[0], daypercent2_img.size[0]) + 5 + max(daychange_img.size[0], daychange2_img.size[0]) + 10,16)) + + img.paste(cost_img, (x_offset, 1)) + img.paste(cost2_img, (x_offset, 9)) + x_offset += max(cost_img.size[0], cost2_img.size[0]) + 4 + img.paste(days_img, (x_offset, 1)) + img.paste(days2_img, (x_offset, 9)) + x_offset += max(days_img.size[0], days2_img.size[0]) + 4 + + img.paste(shares_img, (x_offset, 1)) + img.paste(shares2_img, (x_offset, 9)) + x_offset += max(shares_img.size[0], shares2_img.size[0]) + 4 + img.paste(value_img, (x_offset, 1)) + img.paste(value2_img, (x_offset, 9)) + x_offset += max(value2_img.size[0], value_img.size[0]) + 4 + + img.paste(pnlpercent_img, (x_offset, 1)) + img.paste(pnlpercent2_img, (x_offset, 9)) + x_offset += max(pnlpercent_img.size[0], pnlpercent2_img.size[0]) + 4 + img.paste(pnlchange_img, (x_offset, 1)) + img.paste(pnlchange2_img, (x_offset, 9)) + x_offset += max(pnlchange_img.size[0], pnlchange2_img.size[0]) + 4 + + img.paste(daypercent_img, (x_offset, 1)) + img.paste(daypercent2_img, (x_offset, 9)) + x_offset += max(daypercent_img.size[0], daypercent2_img.size[0]) + 4 + img.paste(daychange_img, (x_offset,1)) + img.paste(daychange2_img, (x_offset, 9)) + except: + pass + except: + pass + image_list.append(stitchedStock) + try: + if all_crypto_settings['chart'] and (cb in portfolio_settings): + try: + image_list.append(img) + except: + pass + except: + pass + image_list.append(self.blank) except Exception as e: pass -# logf = open('log.txt', "a") -# exc_type, exc_obj, exc_tb = sys.exc_info() -# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] -# logf.write(str(e)) -# logf.write('. file: ' + fname) -# logf.write('. line: ' + str(exc_tb.tb_lineno)) -# logf.write('. type: ' + str(exc_type)) -# logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) -# logf.close() finalDisplayImage = self.stitchImage(image_list) self.blank = Image.new('RGB', (10, 32)) @@ -1324,14 +1519,19 @@ class StockTicker(): point_change2 = abs(change) point_changefinal = '{0:.10f}'.format(point_change2).rstrip("0") - point_change = str(point_changefinal) - - + num3 = point_changefinal.split('.') + if len(num3[1]) <= 1: + point_change = '%.2f' % float(point_changefinal) + else: + point_change = str(point_changefinal) + current = float(info["current"]) current_final = '{0:.10f}'.format(current).rstrip("0") - current = str(current_final) - - + num2 = current_final.split('.') + if len(num2[1]) <= 1: + current = '%.2f' % float(current_final) + else: + current = str(current_final) if not all_commodities_settings['percent']: percent_change = False @@ -1406,9 +1606,7 @@ class StockTicker(): change = float(info['24hr_change']) #TEXT unit = info['unit'] ticker = symbol + '(' + unit + ')' #TEXT - - - + arrow, change = self.getArrow(change, professional=True) if all_commodities_settings["percent"]: @@ -1416,12 +1614,19 @@ class StockTicker(): else: point_change2 = abs(change) point_changefinal = '{0:.10f}'.format(point_change2).rstrip("0") - change = str(point_changefinal) - - + num3 = point_changefinal.split('.') + if len(num3[1]) <= 1: + change = '%.2f' % float(point_changefinal) + else: + change = str(point_changefinal) + current = float(info["current"]) current_final = '{0:.10f}'.format(current).rstrip("0") - current = str(current_final) + num2 = current_final.split('.') + if len(num2[1]) <= 1: + current = '%.2f' % float(current_final) + else: + current = str(current_final) midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT @@ -1661,6 +1866,7 @@ class StockTicker(): self.blank = Image.new('RGB', (10, 32)) return finalDisplayImage + def getStockImage(self): f = open('csv/stocks_settings.json', 'r') @@ -1673,12 +1879,30 @@ class StockTicker(): image_list.append(self.blank) else: image_list = [] - - - - + + if all_stocks_settings['chart']: + try: + f = open('csv/portfolio_settings.json', 'r') + portfolio_settings = json.load(f)['symbols'] + f.close() + except: + pass + + try: + if all_stocks_settings['prepost']: + try: + f = open('csv/prepost_settings.json', 'r') + prepost_settings = json.load(f) + f.close() + except: + pass + except: + pass + stock_info = all_stocks_settings['symbols'] symbols = list(stock_info.keys()) + timenow = datetime.now(ny_zone).replace(tzinfo=None).strftime("%H:%M:%S") + weekday = datetime.now(ny_zone).replace(tzinfo=None).weekday() for i, symbol in enumerate(symbols): @@ -1687,27 +1911,19 @@ class StockTicker(): change = float(info['change']) #TEXT ticker = symbol #TEXT - arrow, change = self.getArrow(change) percent_change = '%.2f' % abs(float(info['percent_change'])) + '%' point_change = '%.2f' % abs(change) - - current = '%.2f' % float(info['current']) #TEXT - - if not all_stocks_settings['percent']: percent_change = False if not all_stocks_settings['point']: point_change = False - - - midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT if all_stocks_settings['logos']: @@ -1721,30 +1937,194 @@ class StockTicker(): stitchedStock = midFrame else: stitchedStock = midFrame - + + try: + if all_stocks_settings['prepost']: + font = ImageFont.load("./fonts/6x13.pil") + time_font = ImageFont.load("./fonts/5x8.pil") + prepost_time = prepost_settings[symbol]['time_now'] + + if ((timenow < "09:30:00" and timenow > "04:00:00") and (weekday <= 4)): #premarket + try: + preprice = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['preprice'])) + prechange = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['prechange'])) + prepercent = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['prepercent'])) + + premkt_img = self.textImage('Pre-Mkt', font, r=255, g=255, b=255) + if '-' in prepost_settings[symbol]['Pre-market']['prechange']: + preprice_img = self.textImage(preprice, font, r = 255, g = 0 , b = 0) + prechange_img = self.textImage(prechange, font, r = 255, g = 0, b = 0) + prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=255, g=0, b=0) + arrow = Image.open('logos/down-tiny.png') + elif prepost_settings[symbol]['Pre-market']['prechange'] == '0.00': + preprice_img = self.textImage(preprice, font, r = 200, g = 200 , b = 200) + prechange_img = self.textImage(prechange, font, r = 200, g = 200, b = 200) + prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=200, g=200, b=200) + arrow = Image.open('logos/up-tiny2.png') + else: + preprice_img = self.textImage(preprice, font, r = 0, g = 255 , b = 0) + prechange_img = self.textImage(prechange, font, r = 0, g = 255, b = 0) + prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=0, g=255, b=0) + arrow = Image.open('logos/up-tiny.png') + time_img = self.textImage(prepost_time, time_font, r=255,g=255,b=255) + + prepost_img = Image.new('RGB', (10 + max(premkt_img.size[0] + prepercent_img.size[0], preprice_img.size[0] + 3 + prechange_img.size[0] + arrow.size[0]),32)) + prepost_img.paste(premkt_img, (0,0)) + prepost_img.paste(prepercent_img, (premkt_img.size[0], 1)) + prepost_img.paste(preprice_img,(0,12)) + prepost_img.paste(time_img, (0, 24)) + prepost_img.paste(arrow, (preprice_img.size[0],18)) + prepost_img.paste(prechange_img, (preprice_img.size[0] + arrow.size[0] + 3,12)) + except: + pass + + elif ((timenow < "04:00:00" or timenow > "16:00:00") and (weekday <= 4)) or (weekday > 4): #postmarket + try: + postprice = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postprice'])) + postchange = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postchange'])) + postpercent = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postpercent'])) + + postmkt_img = self.textImage('After-Hrs', font, r=255, g=255, b=255) + if '-' in prepost_settings[symbol]['Post-market']['postchange']: + postprice_img = self.textImage(postprice, font, r = 255, g = 0, b = 0) + postchange_img = self.textImage(postchange, font, r = 255, g = 0, b = 0) + postpercent_img = self.textImage('('+postpercent +'%'+')', font, r=255, g=0, b=0) + arrow = Image.open('logos/down-tiny.png') + elif prepost_settings[symbol]['Post-market']['postchange'] == '0.00': + postprice_img = self.textImage(postprice, font, r = 200, g = 200 , b = 200) + postchange_img = self.textImage(postchange, font, r = 200, g = 200, b = 200) + postpercent_img = self.textImage('('+postpercent + '%' + ')', font, r=200, g=200, b=200) + arrow = Image.open('logos/up-tiny2.png') + else: + postprice_img = self.textImage(postprice, font, r =0, g = 255 , b = 0) + postchange_img = self.textImage(postchange, font, r = 0, g = 255, b = 0) + postpercent_img = self.textImage('(' + postpercent + '%'+')', font, r=0, g=255, b=0) + arrow = Image.open('logos/up-tiny.png') + time_img = self.textImage(prepost_time, time_font, r=255,g=255,b=255) + + prepost_img = Image.new('RGB', (10 + max(postmkt_img.size[0] + postpercent_img.size[0], postprice_img.size[0] + 3 + postchange_img.size[0] + arrow.size[0]) , 32)) + prepost_img.paste(postmkt_img, (0,0)) + prepost_img.paste(postpercent_img, (postmkt_img.size[0], 1)) + prepost_img.paste(postprice_img,(0,12)) + prepost_img.paste(time_img, (0, 24)) + prepost_img.paste(arrow, (postprice_img.size[0],18)) + prepost_img.paste(postchange_img, (postprice_img.size[0] + arrow.size[0] + 3,12)) + except: + pass + + except: + pass + + try: + if all_stocks_settings['chart'] and (symbol in portfolio_settings): #IF USER INPUTTED PORTFOLIO SETTINGS, DISPLAY PORTFOLIO INFO + try: + cost = portfolio_settings[symbol]['cost'] + day = portfolio_settings[symbol]['day'] + shares = portfolio_settings[symbol]['shares'] + + original_value = float(cost) * float(shares) + new_value = float(info['current']) * float(shares) + value_day_change_percent = ((float(info['percent_change'])/100) * new_value) + + font = ImageFont.load("./fonts/5x8.pil") + cost_img = self.textImage('Cost', font, r = 255, g = 255 , b = 255) + cost2_img = self.textImage(cost, font, r = 0, g = 255, b = 0) + shares_img = self.textImage('Shares', font, r = 255, g = 255 , b = 255) + shares2_img = self.textImage(shares, font, r = 0, g = 255, b = 0) + + pnlchange = new_value - original_value + pnlpercent = ((new_value - original_value) / original_value) * 100 + + pnlpercent_img = self.textImage('P/L%', font, r = 255, g = 255 , b = 255) + if pnlpercent >= 0: + pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 0, g = 255, b = 0) + else: + pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 255, g = 0, b = 0) + + daypercent_img = self.textImage('Day%', font, r = 255, g = 255 , b = 255) + if float(info['percent_change']) >= 0: + daypercent2_img = self.textImage(str('%.2f' % abs(float(info['percent_change']))) +'%', font, r = 0, g = 255, b = 0) + else: + daypercent2_img = self.textImage(str('%.2f' % abs(float(info['percent_change'])))+'%', font, r = 255, g = 0, b = 0) + + days_img = self.textImage('Days', font, r = 255, g = 255 , b = 255) + days2_img = self.textImage(day, font, r = 0, g = 255, b = 0) + value_img = self.textImage('Value', font, r = 255, g = 255 , b = 255) + value2_img = self.textImage(str('%.2f' % abs(original_value)), font, r = 0, g = 255, b = 0) + + pnlchange_img = self.textImage('P/L$', font, r = 255, g = 255 , b = 255) + if pnlchange >= 0: + pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 0, g = 255, b = 0) + else: + pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 255, g = 0, b = 0) + + daychange_img = self.textImage('Day$', font, r = 255, g = 255 , b = 255) + if value_day_change_percent >= 0: + daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 0, g = 255, b = 0) + else: + daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 255, g = 0, b = 0) + + x_offset = 0 + + img = Image.new('RGB', (max(cost_img.size[0], cost2_img.size[0], days_img.size[0], days2_img.size[0]) + 7 + + max(shares_img.size[0], shares2_img.size[0], value2_img.size[0], value_img.size[0]) + 7 + + max(pnlpercent_img.size[0], pnlpercent2_img.size[0], pnlchange_img.size[0], pnlchange2_img.size[0]) + 7 + + max(daypercent_img.size[0], daypercent2_img.size[0], daychange_img.size[0], daychange2_img.size[0]) + 15, 32)) + + img.paste(cost_img, (x_offset, 0)) + img.paste(cost2_img, (x_offset, 8)) + img.paste(days_img, (x_offset, 16)) + img.paste(days2_img, (x_offset, 24)) + x_offset += max(cost_img.size[0], cost2_img.size[0], days_img.size[0], days2_img.size[0]) + 7 + + img.paste(shares_img, (x_offset, 0)) + img.paste(shares2_img, (x_offset, 8)) + img.paste(value_img, (x_offset, 16)) + img.paste(value2_img, (x_offset, 24)) + x_offset += max(shares_img.size[0], shares2_img.size[0], value2_img.size[0], value_img.size[0]) + 7 + + img.paste(pnlpercent_img, (x_offset, 0)) + img.paste(pnlpercent2_img, (x_offset, 8)) + img.paste(pnlchange_img, (x_offset, 16)) + img.paste(pnlchange2_img, (x_offset, 24)) + x_offset += max(pnlpercent_img.size[0], pnlpercent2_img.size[0], pnlchange_img.size[0], pnlchange2_img.size[0]) + 7 + + img.paste(daypercent_img, (x_offset, 0)) + img.paste(daypercent2_img, (x_offset, 8)) + img.paste(daychange_img, (x_offset,16)) + img.paste(daychange2_img, (x_offset, 24)) + except: + pass + except: + pass + image_list.append(stitchedStock) - - + + try: + if all_stocks_settings['prepost']: + try: + image_list.append(prepost_img) + except: + pass + except: + pass + + try: + if all_stocks_settings['chart'] and (symbol in portfolio_settings): + try: + image_list.append(img) + except: + pass + except: + pass image_list.append(self.blank) except Exception as e: pass -# logf = open('log.txt', "a") -# exc_type, exc_obj, exc_tb = sys.exc_info() -# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] -# logf.write(str(e)) -# logf.write('. file: ' + fname) -# logf.write('. line: ' + str(exc_tb.tb_lineno)) -# logf.write('. type: ' + str(exc_type)) -# logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) -# logf.close() - - finalDisplayImage = self.stitchImage(image_list) - - return finalDisplayImage + def getStockProfessional(self): self.blank = Image.new('RGB', (0, 16)) @@ -1759,11 +2139,31 @@ class StockTicker(): image_list.append(self.blank) else: image_list = [] - - + + if all_stocks_settings['chart']: + try: + f = open('csv/portfolio_settings.json', 'r') + portfolio_settings = json.load(f)['symbols'] + f.close() + except: + pass + + try: + if all_stocks_settings['prepost']: + try: + f = open('csv/prepost_settings.json', 'r') + prepost_settings = json.load(f) + f.close() + except: + pass + except: + pass + stock_info = all_stocks_settings['symbols'] symbols = list(stock_info.keys()) - + timenow = datetime.now(ny_zone).replace(tzinfo=None).strftime("%H:%M:%S") + weekday = datetime.now(ny_zone).replace(tzinfo=None).weekday() + for i, symbol in enumerate(symbols): try: @@ -1772,8 +2172,6 @@ class StockTicker(): change = float(info['change'])#TEXT ticker = symbol #TEXT - - arrow, change = self.getArrow(change, professional=True) if all_stocks_settings["percent"]: @@ -1807,30 +2205,199 @@ class StockTicker(): stitchedStock = midFrame else: stitchedStock = midFrame - + + try: + if all_stocks_settings['prepost']: + font = ImageFont.load("./fonts/5x8.pil") + # prepost_time = prepost_settings[symbol]['time_now'] + + if ((timenow < "09:30:00" and timenow > "04:00:00") and (weekday <= 4)): #premarket + try: + preprice = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['preprice'])) + prechange = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['prechange'])) + prepercent = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['prepercent'])) + + premkt_img = self.textImage('Pre-Mkt', font, r=255, g=255, b=255) + if '-' in prepost_settings[symbol]['Pre-market']['prechange']: + preprice_img = self.textImage(preprice, font, r = 255, g = 0 , b = 0) + prechange_img = self.textImage(prechange, font, r = 255, g = 0, b = 0) + prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=255, g=0, b=0) + arrow = Image.open('logos/down-tiny.png') + elif prepost_settings[symbol]['Pre-market']['prechange'] == '0.00': + preprice_img = self.textImage(preprice, font, r = 200, g = 200 , b = 200) + prechange_img = self.textImage(prechange, font, r = 200, g = 200, b = 200) + prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=200, g=200, b=200) + arrow = Image.open('logos/up-tiny2.png') + else: + preprice_img = self.textImage(preprice, font, r = 0, g = 255 , b = 0) + prechange_img = self.textImage(prechange, font, r = 0, g = 255, b = 0) + prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=0, g=255, b=0) + arrow = Image.open('logos/up-tiny.png') + # time_img = self.textImage(prepost_time, font, r=255,g=255,b=255) + prepost_img = Image.new('RGB', (max(premkt_img.size[0] + prepercent_img.size[0], preprice_img.size[0] + 2 + prechange_img.size[0] + arrow.size[0]) + 10, 16)) + prepost_img.paste(premkt_img, (0,0)) + prepost_img.paste(prepercent_img, (premkt_img.size[0], 0)) + prepost_img.paste(preprice_img,(0,7)) + # prepost_img.paste(time_img, (preprice_img.size[0] + prechange_img.size[0] + 2 + arrow.size[0], 8)) + prepost_img.paste(arrow, (preprice_img.size[0],10)) + prepost_img.paste(prechange_img, (preprice_img.size[0] + arrow.size[0] + 2,7)) + except: + pass + + elif ((timenow < "04:00:00" or timenow > "16:00:00") and (weekday <= 4)) or (weekday > 4): #postmarket + try: + postprice = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postprice'])) + postchange = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postchange'])) + postpercent = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postpercent'])) + + postmkt_img = self.textImage('After-Hrs', font, r=255, g=255, b=255) + if '-' in prepost_settings[symbol]['Post-market']['postchange']: + postprice_img = self.textImage(postprice, font, r = 255, g = 0, b = 0) + postchange_img = self.textImage(postchange, font, r = 255, g = 0, b = 0) + postpercent_img = self.textImage('('+postpercent +'%'+')', font, r=255, g=0, b=0) + arrow = Image.open('logos/down-tiny.png') + elif prepost_settings[symbol]['Post-market']['postchange'] == '0.00': + postprice_img = self.textImage(postprice, font, r = 200, g = 200, b = 200) + postchange_img = self.textImage(postchange, font, r = 200, g = 200, b = 200) + postpercent_img = self.textImage('('+postpercent +'%'+')', font, r=200, g=200, b=200) + arrow = Image.open('logos/up-tiny2.png') + else: + postprice_img = self.textImage(postprice, font, r =0, g = 255 , b = 0) + postchange_img = self.textImage(postchange, font, r = 0, g = 255, b = 0) + postpercent_img = self.textImage('(' + postpercent + '%'+')', font, r=0, g=255, b=0) + arrow = Image.open('logos/up-tiny.png') + #time_img = self.textImage(prepost_time, font, r=255,g=255,b=255) + + prepost_img = Image.new('RGB', (10 + max(postmkt_img.size[0] + postpercent_img.size[0], postprice_img.size[0] + 2 + postchange_img.size[0] + arrow.size[0]) , 16)) + prepost_img.paste(postmkt_img, (0,0)) + prepost_img.paste(postpercent_img, (postmkt_img.size[0], 0)) + prepost_img.paste(postprice_img,(0,7)) + #prepost_img.paste(time_img, (0, 12)) + prepost_img.paste(arrow, (postprice_img.size[0],10)) + prepost_img.paste(postchange_img, (postprice_img.size[0] + arrow.size[0] + 2,7)) + except: + pass + + except: + pass + + try: + if all_stocks_settings['chart'] and (symbol in portfolio_settings): #IF USER INPUTTED PORTFOLIO SETTINGS, DISPLAY PORTFOLIO INFO + try: + cost = portfolio_settings[symbol]['cost'] + day = portfolio_settings[symbol]['day'] + shares = portfolio_settings[symbol]['shares'] + + original_value = float(cost) * float(shares) + new_value = float(info['current']) * float(shares) + value_day_change_percent = ((float(info['percent_change'])/100) * new_value) + + font = ImageFont.load("./fonts/5x8.pil") + cost_img = self.textImage('Cost', font, r = 255, g = 255 , b = 255) + cost2_img = self.textImage(cost, font, r = 0, g = 255, b = 0) + shares_img = self.textImage('Shares', font, r = 255, g = 255 , b = 255) + shares2_img = self.textImage(shares, font, r = 0, g = 255, b = 0) + + pnlchange = new_value - original_value + pnlpercent = ((new_value - original_value) / original_value) * 100 + + pnlpercent_img = self.textImage('P/L%', font, r = 255, g = 255 , b = 255) + if pnlpercent >= 0: + pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 0, g = 255, b = 0) + else: + pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 255, g = 0, b = 0) + + + daypercent_img = self.textImage('Day%', font, r = 255, g = 255 , b = 255) + if float(info['percent_change']) >= 0: + daypercent2_img = self.textImage(str('%.2f' % abs(float(info['percent_change']))) +'%', font, r = 0, g = 255, b = 0) + else: + daypercent2_img = self.textImage(str('%.2f' % abs(float(info['percent_change'])))+'%', font, r = 255, g = 0, b = 0) + + days_img = self.textImage('Days', font, r = 255, g = 255 , b = 255) + days2_img = self.textImage(day, font, r = 0, g = 255, b = 0) + value_img = self.textImage('Value', font, r = 255, g = 255 , b = 255) + value2_img = self.textImage(str('%.2f' % abs(original_value)), font, r = 0, g = 255, b = 0) + + pnlchange_img = self.textImage('P/L$', font, r = 255, g = 255 , b = 255) + if pnlchange >= 0: + pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 0, g = 255, b = 0) + else: + pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 255, g = 0, b = 0) + + daychange_img = self.textImage('Day$', font, r = 255, g = 255 , b = 255) + if value_day_change_percent >= 0: + daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 0, g = 255, b = 0) + else: + daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 255, g = 0, b = 0) + + x_offset = 0 + + img = Image.new('RGB', (max(cost_img.size[0], cost2_img.size[0]) + 5 + max(days_img.size[0], days2_img.size[0]) + 5 + + max(shares_img.size[0], shares2_img.size[0]) + 5 + max(value2_img.size[0], value_img.size[0]) + 5 + + max(pnlpercent_img.size[0], pnlpercent2_img.size[0]) + 5 + max(pnlchange_img.size[0], pnlchange2_img.size[0]) + 5 + + max(daypercent_img.size[0], daypercent2_img.size[0]) + 5 + max(daychange_img.size[0], daychange2_img.size[0]) + 10,16)) + + img.paste(cost_img, (x_offset, 1)) + img.paste(cost2_img, (x_offset, 9)) + x_offset += max(cost_img.size[0], cost2_img.size[0]) + 4 + img.paste(days_img, (x_offset, 1)) + img.paste(days2_img, (x_offset, 9)) + x_offset += max(days_img.size[0], days2_img.size[0]) + 4 + + img.paste(shares_img, (x_offset, 1)) + img.paste(shares2_img, (x_offset, 9)) + x_offset += max(shares_img.size[0], shares2_img.size[0]) + 4 + img.paste(value_img, (x_offset, 1)) + img.paste(value2_img, (x_offset, 9)) + x_offset += max(value2_img.size[0], value_img.size[0]) + 4 + + img.paste(pnlpercent_img, (x_offset, 1)) + img.paste(pnlpercent2_img, (x_offset, 9)) + x_offset += max(pnlpercent_img.size[0], pnlpercent2_img.size[0]) + 4 + img.paste(pnlchange_img, (x_offset, 1)) + img.paste(pnlchange2_img, (x_offset, 9)) + x_offset += max(pnlchange_img.size[0], pnlchange2_img.size[0]) + 4 + + img.paste(daypercent_img, (x_offset, 1)) + img.paste(daypercent2_img, (x_offset, 9)) + x_offset += max(daypercent_img.size[0], daypercent2_img.size[0]) + 4 + img.paste(daychange_img, (x_offset,1)) + img.paste(daychange2_img, (x_offset, 9)) + except: + pass + except: + pass + image_list.append(stitchedStock) + + try: + if all_stocks_settings['prepost']: + try: + image_list.append(prepost_img) + except: + pass + except: + pass - + try: + if all_stocks_settings['chart'] and (symbol in portfolio_settings): + try: + image_list.append(img) + except: + pass + except: + pass + image_list.append(self.blank) except Exception as e: pass -# logf = open('log.txt', "a") -# exc_type, exc_obj, exc_tb = sys.exc_info() -# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] -# logf.write(str(e)) -# logf.write('. file: ' + fname) -# logf.write('. line: ' + str(exc_tb.tb_lineno)) -# logf.write('. type: ' + str(exc_type)) -# logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) -# logf.close() - finalDisplayImage = self.stitchImage(image_list) - - self.blank = Image.new('RGB', (10, 32)) return finalDisplayImage + def getNewsImage(self): @@ -2175,16 +2742,15 @@ class StockTicker(): for league in leagues: try: x_offset = 0 - if (league =='PGA') or (league == 'LPGA') or (league == 'PGA_EU'): + if (league =='PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'): img = Image.new('RGB', (10000, 32)) else: img = Image.new('RGB', (10000, 32)) league_info = leagues_info[league] - try: - league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB') - if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'): + league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)) + if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'): x_offset += self.blank.size[0] else: img.paste(league_logo, (x_offset,0)) @@ -2192,219 +2758,424 @@ class StockTicker(): except: pass - - small_font = ImageFont.load("./fonts/5x7.pil") - med_font = ImageFont.load("./fonts/7x14B.pil") - large_font = ImageFont.load("./fonts/9x18B.pil") - extra_small_font = ImageFont.load("./fonts/4x6.pil") try: sports_info = self.readSportsCSV(league) except: pass + med_font = ImageFont.load("./fonts/7x14B.pil") + large_font = ImageFont.load("./fonts/9x18B.pil") + extra_small_font = ImageFont.load("./fonts/4x6.pil") + buff_size = 25 - for match in league_info: + if league == 'UFC': + try: + small_font = ImageFont.load("./fonts/6x10.pil") + date_img = self.textImage(league_info[0]['date'], small_font, r=0,g=150,b=255) + eventname_img = self.textImage(league_info[0]['name'].upper(), med_font, r=255, g=0, b=0) + venue_img = self.textImage(league_info[0]['venue'], small_font, r=255, g=255, b=0) + city_img = self.textImage(league_info[0]['city'], small_font, r=255, g=255, b=255) + try: + country_img = self.textImage(league_info[0]['country'], small_font, r=255, g=128, b=0) + except: + pass + broadcast_img = self.textImage(league_info[0]['broadcast'], small_font, r=255, g=0, b=0) + time_img = self.textImage(league_info[0]['time'], small_font, r =0, g=150, b=255) - dateEvent = match['date'].replace('-', '.') - date_timage = self.textImage(dateEvent, small_font, r=255, g=255, b=255) + try: + img.paste(country_img, (x_offset + venue_img.size[0] + 5 + city_img.size[0] +5, 13)) + except: + country_img = 0 + pass + img.paste(eventname_img, (x_offset, 0)) + img.paste(city_img, (x_offset+ venue_img.size[0] + 5, 13)) + img.paste(venue_img, (x_offset,13)) + img.paste(broadcast_img, (x_offset + date_img.size[0] + 5 + time_img.size[0] + 5, 23)) + img.paste(date_img, (x_offset, 23)) + img.paste(time_img, (x_offset + date_img.size[0] + 5, 23)) + try: + x_offset = 5 + max(x_offset + eventname_img.size[0], x_offset + venue_img.size[0] + 5 + city_img.size[0] + 5 + country_img.size[0], x_offset + date_img.size[0] + 5 + time_img.size[0] + 5 + broadcast_img.size[0]) + except: + x_offset = 5 + max(x_offset + eventname_img.size[0], x_offset + venue_img.size[0] + 5 + city_img.size[0] + 5, x_offset + date_img.size[0] + 5 + time_img.size[0] + 5 + broadcast_img.size[0]) - if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'): - event = match['event'] - venue = match['venue'] - city = match['city'] - country = match['country'] - season = match['season'] + for fight in league_info[0]['fights']: + try: + if time != 'past': + fighter1_img = Image.open('logos/ufc/{}.png'.format(fight['fighter1id'])) + elif time == 'past': + fighter1_img = Image.open('logos/ufc_past/{}.png'.format(fight['fighter1id'])) + #fighter1_img.thumbnail((9000,32)) + except: + fighter1_img = Image.open('logos/unknown.png') + pass + try: + if time != 'past': + fighter2_img = Image.open('logos/ufc/{}.png'.format(fight['fighter2id'])) + elif time == 'past': + fighter2_img = Image.open('logos/ufc_past/{}.png'.format(fight['fighter2id'])) + #fighter2_img.thumbnail((9000,32)) + except: + fighter2_img = Image.open('logos/unknown.png') + pass + weight_img = self.textImage(fight['weight_div'].upper(), extra_small_font, r=255,g=255,b=255) + age1_img = self.textImage(fight['fighter1age'], extra_small_font, r=255,g=255,b=255) + age2_img = self.textImage(fight['fighter2age'], extra_small_font, r=255,g=255,b=255) + age_img = self.textImage('AGE', extra_small_font, r=255,g=0,b=0) + + height1_img = self.textImage(fight['fighter1height'], extra_small_font, r=255,g=255,b=255) + height2_img = self.textImage(fight['fighter2height'], extra_small_font, r=255,g=255,b=255) + height_img = self.textImage('HEIGHT', extra_small_font, r=255,g=0,b=0) - if time != 'future': - golf_standings1 = match['golf_standings'][::2] - golf_standings2 = match['golf_standings'][1::2] + weight1_img = self.textImage(fight['fighter1weight'], extra_small_font, r=255,g=255,b=255) + weight2_img = self.textImage(fight['fighter2weight'], extra_small_font, r=255,g=255,b=255) + weights_img = self.textImage('WEIGHT', extra_small_font, r=255,g=0,b=0) - img.paste(league_logo, (x_offset, 0)) - x_offset += league_logo.size[0] + 2 + reach1_img = self.textImage(fight['fighter1reach'], extra_small_font, r=255,g=255,b=255) + reach2_img = self.textImage(fight['fighter2reach'], extra_small_font, r=255,g=255,b=255) + reach_img = self.textImage('REACH', extra_small_font, r=255,g=0,b=0) - if time == 'future': + name1_img = self.textImage(fight['fighter1name'], extra_small_font, r=255,g=255,b=255) + record1_img = self.textImage(fight['fighter1record'], extra_small_font, r=255, g=255, b=255) - event_timage = self.textImage(event, med_font, r=255, g=255, b=0) - venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0) - city_timage = self.textImage(city, small_font, r=255, g=255, b=255) - country_timage = self.textImage(country, small_font, r=255, g=255, b=255) - date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171) - season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255) - season_timage = self.textImage(season, small_font, r=255, g=255, b=255) + name2_img = self.textImage(fight['fighter2name'], extra_small_font, r=255,g=255,b=255) + record2_img = self.textImage(fight['fighter2record'], extra_small_font, r=255, g=255, b=255) - #date - img.paste(date1_timage, (x_offset + 2, 26)) - img.paste(date_timage, (x_offset + date1_timage.size[0] + 3, 26)) - #event - img.paste(event_timage, (x_offset + 2, 0)) - #venue - img.paste(venue_timage,(x_offset + 2, 16)) - #country - img.paste(country_timage,(x_offset + event_timage.size[0] + 5,5)) - #city - img.paste(city_timage,(x_offset + 15 + venue_timage.size[0], 16)) - #season - img.paste(season1_timage,(x_offset + 2 + date1_timage.size[0] + date_timage.size[0] + 20,26)) - img.paste(season_timage,(x_offset + 2 + date1_timage.size[0] + date_timage.size[0] + 20 + season1_timage.size[0],26)) + if time != 'past': + odds1_img = self.textImage(fight['fighter1odds'], extra_small_font, r=0, g=255, b=0) + #odds2_img = self.textImage(fight['fighter2odds'], extra_small_font, r=0, g=255, b=0) + elif time == 'past': + if fight['fighter1win']: + win1_img = self.textImage('WIN', extra_small_font, r=0, g=255, b=0) + elif not fight['fighter1win'] and not fight['fighter2win']: + win1_img = self.textImage('DRAW', extra_small_font, r=80, g=80, b=80) + else: + win1_img = self.textImage('LOSS', extra_small_font, r=0, g=255, b=0) - x_offset += max(2 + event_timage.size[0] + country_timage.size[0] + 5, 2 + venue_timage.size[0] + city_timage.size[0] + 15, 2 + date1_timage.size[0] + date_timage.size[0] + 20 + season1_timage.size[0] + season_timage.size[0] + 3) + max_fighter1_pic = max(fighter1_img.size[0], name1_img.size[0], record1_img.size[0]) + draw = ImageDraw.Draw(img, "RGBA") + img.paste(fighter1_img, (x_offset + int(max_fighter1_pic/2) - int(fighter1_img.size[0]/2), 0), mask=fighter1_img) + try: + country1_img = Image.open('logos/ufc_countries/{}'.format(fight['fighter1country'].split('/')[-1].split('&')[0])) + country1_img.thumbnail((9000,12)) + img.paste(country1_img,(x_offset, 0)) + except: + pass + + draw.rectangle([(x_offset,32),(x_offset + max(name1_img.size[0],record1_img.size[0])-4,21)], fill=(5,5,5,200)) + + draw.text((x_offset + int(max_fighter1_pic/2) - int(name1_img.size[0]/2),21), fight['fighter1name'], fill=(255,255,255),font=extra_small_font) + #img.paste(name1_img, (x_offset + int(max_fighter1_pic/2) - int(name1_img.size[0]/2),21)) + draw.text((x_offset + int(max_fighter1_pic/2) - int(record1_img.size[0]/2),27), fight['fighter1record'], fill=(255,255,0),font=extra_small_font) + #img.paste(record1_img, (x_offset + int(max_fighter1_pic/2) - int(record1_img.size[0]/2), 27)) + x_offset += max(fighter1_img.size[0], name1_img.size[0], record1_img.size[0]) + + + widest = x_offset + int(max(weight_img.size[0], age1_img.size[0] + 3 + age_img.size[0] + 3 + age2_img.size[0], height1_img.size[0] + 3 + height_img.size[0] + 3 + height2_img.size[0], weight1_img.size[0] + 3 + weights_img.size[0] + 3 + weight2_img.size[0], reach1_img.size[0] + 3 + reach_img.size[0] + 3 + reach2_img.size[0])/2) + largest = max(age_img.size[0],weights_img.size[0],height_img.size[0],reach_img.size[0]) + + img.paste(weight_img,(widest - int(weight_img.size[0]/2), 0)) + if time != 'past': + draw.text((widest - int(weight_img.size[0]/2) - odds1_img.size[0] - 2,0), fight['fighter1odds'], fill=(0,255,0),font=extra_small_font) + # img.paste(odds1_img, (widest - int(weight_img.size[0]/2) - odds1_img.size[0] - 2,0)) + elif time == 'past': + if fight['fighter1win']: + draw.text((widest - int(weight_img.size[0]/2) - win1_img.size[0] - 2,0), 'WIN', fill=(0,255,0),font=extra_small_font) + elif not fight['fighter1win'] and not fight['fighter2win']: + draw.text((widest - int(weight_img.size[0]/2) - win1_img.size[0] - 2,0), 'DRAW', fill=(80,80,80),font=extra_small_font) + else: + draw.text((widest - int(weight_img.size[0]/2) - win1_img.size[0] - 2,0), 'LOSS', fill=(255,0,0),font=extra_small_font) + + img.paste(age1_img,(widest - int(largest/2) - age1_img.size[0] - 3, 7)) + img.paste(age_img,(widest - int(age_img.size[0]/2),7)) + img.paste(age2_img, (widest + int(largest/2) + 3, 7)) + + img.paste(height1_img,(widest - int(largest/2) - height1_img.size[0] - 3, 13)) + img.paste(height_img,(widest - int(height_img.size[0]/2),13)) + img.paste(height2_img, (widest + int(largest/2) + 3, 13)) + + img.paste(weight1_img,(widest - int(largest/2) - weight1_img.size[0] - 3, 19)) + img.paste(weights_img,(widest - int(weights_img.size[0]/2),19)) + img.paste(weight2_img, (widest + int(largest/2) + 3, 19)) + + img.paste(reach1_img,(widest - int(largest/2) - reach1_img.size[0] - 3, 25)) + img.paste(reach_img,(widest - int(reach_img.size[0]/2),25)) + img.paste(reach2_img, (widest + int(largest/2) + 3, 25)) + + x_offset = widest + widest - x_offset + 2 + + max_fighter2_pic = max(fighter2_img.size[0], name2_img.size[0], record2_img.size[0]) + img.paste(fighter2_img, (x_offset + int(max_fighter2_pic/2) - int(fighter2_img.size[0]/2), 0), mask=fighter2_img) + + draw.rectangle([(x_offset,32),(x_offset + max(name2_img.size[0],record2_img.size[0])-4,21)], fill=(5,5,5,200)) + + draw.text((x_offset + int(max_fighter2_pic/2) - int(name2_img.size[0]/2),21), fight['fighter2name'], fill=(255,255,255),font=extra_small_font) + #img.paste(name1_img, (x_offset + int(max_fighter1_pic/2) - int(name1_img.size[0]/2),21)) + draw.text((x_offset + int(max_fighter2_pic/2) - int(record2_img.size[0]/2),27), fight['fighter2record'], fill=(255,255,0),font=extra_small_font) + #img.paste(record1_img, (x_offset + int(max_fighter1_pic/2) - int(record1_img.size[0]/2), 27)) + x_offset += max(fighter2_img.size[0], name2_img.size[0], record2_img.size[0]) + 25 + + + if time != 'past': + draw.text((widest + int(weight_img.size[0]/2) + 2,0), fight['fighter2odds'], fill=(0,255,0),font=extra_small_font) + #img.paste(odds2_img, (widest + int(weight_img.size[0]/2) + 2,0)) + elif time == 'past': + if fight['fighter2win']: + draw.text((widest + int(weight_img.size[0]/2) + 2,0), 'WIN', fill=(0,255,0),font=extra_small_font) + elif not fight['fighter2win'] and not fight['fighter1win']: + draw.text((widest + int(weight_img.size[0]/2) + 2,0), 'DRAW', fill=(80,80,80),font=extra_small_font) + else: + draw.text((widest + int(weight_img.size[0]/2) + 2,0), 'LOSS', fill=(255,0,0),font=extra_small_font) + try: + country2_img = Image.open('logos/ufc_countries/{}'.format(fight['fighter2country'].split('/')[-1].split('&')[0])) + country2_img.thumbnail((9000,12)) + img.paste(country2_img,(x_offset-country2_img.size[0]-25, 0)) + except: + pass + except: + pass + + # DONT FORGET TO CHANGE DIRECTORY FOR PAST UFC GAMES + + else: + small_font = ImageFont.load("./fonts/5x7.pil") + for match in league_info: + + try: + dateEvent = match['date2'] + except: + dateEvent = match['date'].replace('-', '.') + date_timage = self.textImage(dateEvent, small_font, r=255, g=255, b=255) + + if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'): + event = match['event'] + venue = match['venue'] + city = match['city'] + country = match['country'] + season = match['season'] + + if (time != 'future') and (league != 'LIV'): + golf_standings1 = match['golf_standings'][::2] + golf_standings2 = match['golf_standings'][1::2] + elif (time!= 'future') and (league == 'LIV'): + golf_standings1 = match['golf_standings'][0][::2] + golf_standings2 = match['golf_standings'][0][1::2] + golf_standings1_teams = match['golf_standings'][1][::2] + golf_standings2_teams = match['golf_standings'][1][1::2] + + img.paste(league_logo, (x_offset, 0)) + x_offset += league_logo.size[0] + 2 + + if time == 'future': + + event_timage = self.textImage(event, med_font, r=255, g=255, b=0) + venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0) + city_timage = self.textImage(city, small_font, r=255, g=255, b=255) + country_timage = self.textImage(country, small_font, r=255, g=255, b=255) + date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171) + season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255) + season_timage = self.textImage(season, small_font, r=255, g=255, b=255) + + #date + img.paste(date1_timage, (x_offset + 2, 26)) + img.paste(date_timage, (x_offset + date1_timage.size[0] + 3, 26)) + #event + img.paste(event_timage, (x_offset + 2, 0)) + #venue + img.paste(venue_timage,(x_offset + 2, 16)) + #country + img.paste(country_timage,(x_offset + event_timage.size[0] + 5,5)) + #city + img.paste(city_timage,(x_offset + 15 + venue_timage.size[0], 16)) + #season + img.paste(season1_timage,(x_offset + 2 + date1_timage.size[0] + date_timage.size[0] + 20,26)) + img.paste(season_timage,(x_offset + 2 + date1_timage.size[0] + date_timage.size[0] + 20 + season1_timage.size[0],26)) + + x_offset += max(2 + event_timage.size[0] + country_timage.size[0] + 5, 2 + venue_timage.size[0] + city_timage.size[0] + 15, 2 + date1_timage.size[0] + date_timage.size[0] + 20 + season1_timage.size[0] + season_timage.size[0] + 3) + x_offset += buff_size + + else: + event_timage = self.textImage(event, med_font, r=255, g=255, b=0) + venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0) + city_timage = self.textImage(city, small_font, r=255, g=255, b=255) + country_timage = self.textImage(country, small_font, r=255, g=255, b=255) + date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171) + season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255) + season_timage = self.textImage(season, small_font, r=255, g=255, b=255) + + #date + img.paste(date1_timage, (x_offset + 2, 26)) + img.paste(date_timage, (x_offset + date1_timage.size[0] + 3, 26)) + #event + img.paste(event_timage, (x_offset + 2, 0)) + #venue + img.paste(venue_timage,(x_offset + 2, 16)) + #country + img.paste(country_timage,(x_offset + event_timage.size[0] + 5,5)) + #city + img.paste(city_timage,(x_offset + 15 + venue_timage.size[0], 16)) + #season + img.paste(season1_timage,(x_offset + 2 + date1_timage.size[0] + date_timage.size[0] + 20,26)) + img.paste(season_timage,(x_offset + 2 + date1_timage.size[0] + date_timage.size[0] + 20 + season1_timage.size[0],26)) + + x_offset += max(2 + event_timage.size[0] + country_timage.size[0] + 5, 2 + venue_timage.size[0] + city_timage.size[0] + 15, 2 + date1_timage.size[0] + date_timage.size[0] + 20 + season1_timage.size[0] + season_timage.size[0] + 3) + x_offset2 = x_offset + + for each_player in golf_standings1: + symbol1_timage = self.textImage('|', small_font, r=255, g=255, b=0) + img.paste(symbol1_timage, (x_offset + 5, 7)) + golf_standings1_timage = self.textImage(each_player, small_font, r=255, g=255, b=255) + img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 7)) + x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7) + + for each_player2 in golf_standings2: + symbol2_timage = self.textImage('|', small_font, r=255, g=255, b=0) + img.paste(symbol2_timage, (x_offset2 + 5, 20)) + golf_standings2_timage = self.textImage(each_player2, small_font, r=255, g=255, b=255) + img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 20)) + x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7) + + if league == 'LIV': + if x_offset >= x_offset2: + x_offset += 10 + x_offset2 = x_offset + else: + x_offset2 += 10 + x_offset = x_offset2 + + for each_team in golf_standings1_teams: + symbol1_timage = self.textImage('|', small_font, r=0, g=255, b=0) + img.paste(symbol1_timage, (x_offset + 5, 7)) + golf_standings1_timage = self.textImage(each_team, small_font, r=255, g=255, b=255) + img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 7)) + x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7) + for each_team2 in golf_standings2_teams: + symbol2_timage = self.textImage('|', small_font, r=0, g=255, b=0) + img.paste(symbol2_timage, (x_offset2 + 5, 20)) + golf_standings2_timage = self.textImage(each_team2, small_font, r=255, g=255, b=255) + img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 20)) + x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7) + + + if x_offset >= x_offset2: + x_offset += buff_size + else: + x_offset = x_offset2 + x_offset += buff_size + else: + strHomeTeam = match['home_team'] + strAwayTeam = match['away_team'] + + if time != 'future': + intHomeScore = str(match['home_score']) + intAwayScore = str(match['away_score']) + + try: + + home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strHomeTeam]['logo'])) + + except Exception as e: + home_logo = self.textImage(strHomeTeam.replace(' ', '\n'), extra_small_font, r = 255, g = 255, b = 255) + + try: + + away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strAwayTeam]['logo'])) + + except Exception as e: + away_logo = self.textImage(strAwayTeam.replace(' ', '\n'), extra_small_font, r = 255, g = 255, b = 255) + + img.paste(away_logo, (x_offset,0)) + + x_offset += away_logo.size[0] + 4 + + if time == 'future': + try: + start_time = match['time'] + #img.paste(date_timage, (x_offset+5, 0)) + time_img = self.textImage(start_time, small_font, r=255,g=255,b=255) + except: + pass + try: + h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', '')) + except: + pass + try: + a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', '')) + except: + pass + vs_timage = self.textImage('vs', med_font, r = 255, g = 255, b = 255, h_buff = 5) + try: + hc_timage = self.textImage(sports_info[strHomeTeam]['code'], med_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) + except Exception as e: + hc_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255) + try: + ac_timage = self.textImage(sports_info[strAwayTeam]['code'], med_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) + except Exception as e: + ac_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255) + + vs_size = vs_timage.size[0] + ac_timage.size[0] + hc_timage.size[0] + + main_offset = 5 + x_offset + int(max(vs_size, date_timage.size[0])/2) + + try: + img.paste(time_img, (main_offset - int(time_img.size[0]/2), 26)) + except: + pass + img.paste(date_timage, (main_offset - int(date_timage.size[0]/2), 0)) + img.paste(vs_timage, (main_offset - int(vs_timage.size[0]/2),9)) + img.paste(ac_timage, (main_offset - int(vs_timage.size[0]/2) - ac_timage.size[0], 9)) + img.paste(hc_timage, (main_offset + int(vs_timage.size[0]/2),9)) + x_offset = (main_offset + max(int(date_timage.size[0]/2), int(vs_timage.size[0]/2) + hc_timage.size[0]) + 6) + else: + score_image = self.textImage(intAwayScore + '-' + intHomeScore, large_font, h_buff = 5, r = 255, g = 255, b = 255) + try: + h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', '')) + except: + pass + try: + a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', '')) + except: + pass + try: + hc_timage = self.textImage(sports_info[strHomeTeam]['code'], small_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) + except Exception as e: + hc_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255) + try: + ac_timage = self.textImage(sports_info[strAwayTeam]['code'], small_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) + except Exception as e: + ac_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255) + + vs_timage = self.textImage('VS', extra_small_font, r = 255, g = 255, b = 255) + + vs_size = hc_timage.size[0] + ac_timage.size[0] + vs_timage.size[0] + + main_offset = x_offset + int(max(vs_size, date_timage.size[0], score_image.size[0])/2) + img.paste(date_timage,(main_offset - int(date_timage.size[0]/2),0)) + img.paste(vs_timage,(main_offset - int(vs_timage.size[0]/2),10)) + img.paste(ac_timage, (main_offset - int(vs_timage.size[0]/2) - ac_timage.size[0], 9)) + img.paste(score_image, (main_offset - int(score_image.size[0]/2), 15)) + if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore): + ua_image = Image.new("RGB", (ac_timage.size[0] -2, 1)) + ua_image1 = ImageDraw.Draw(ua_image) + ua_image1.line((0,0,ac_timage.size[0]-2,0), fill="red", width = 0) + img.paste(ua_image, (main_offset - int(vs_timage.size[0]/2)-ac_timage.size[0], ac_timage.size[1]+7)) + img.paste(hc_timage, (main_offset + int(vs_timage.size[0]/2),9)) + if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore): + u_image = Image.new("RGB", (hc_timage.size[0] -2, 1)) + u_image1 = ImageDraw.Draw(u_image) + u_image1.line((0,0,hc_timage.size[0]-2,0), fill="red", width = 0) + img.paste(u_image, (main_offset + int(vs_timage.size[0]/2), hc_timage.size[1]+7)) + x_offset = (main_offset + max(int(date_timage.size[0]/2), int(vs_timage.size[0]/2) + hc_timage.size[0], int(score_image.size[0]/2)) + 4) + + img.paste(home_logo, (x_offset,0)) + + x_offset += home_logo.size[0] x_offset += buff_size - else: - event_timage = self.textImage(event, med_font, r=255, g=255, b=0) - venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0) - city_timage = self.textImage(city, small_font, r=255, g=255, b=255) - country_timage = self.textImage(country, small_font, r=255, g=255, b=255) - date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171) - season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255) - season_timage = self.textImage(season, small_font, r=255, g=255, b=255) - - #date - img.paste(date1_timage, (x_offset + 2, 26)) - img.paste(date_timage, (x_offset + date1_timage.size[0] + 3, 26)) - #event - img.paste(event_timage, (x_offset + 2, 0)) - #venue - img.paste(venue_timage,(x_offset + 2, 16)) - #country - img.paste(country_timage,(x_offset + event_timage.size[0] + 5,5)) - #city - img.paste(city_timage,(x_offset + 15 + venue_timage.size[0], 16)) - #season - img.paste(season1_timage,(x_offset + 2 + date1_timage.size[0] + date_timage.size[0] + 20,26)) - img.paste(season_timage,(x_offset + 2 + date1_timage.size[0] + date_timage.size[0] + 20 + season1_timage.size[0],26)) - - x_offset += max(2 + event_timage.size[0] + country_timage.size[0] + 5, 2 + venue_timage.size[0] + city_timage.size[0] + 15, 2 + date1_timage.size[0] + date_timage.size[0] + 20 + season1_timage.size[0] + season_timage.size[0] + 3) - x_offset2 = x_offset - - for each_player in golf_standings1: - symbol1_timage = self.textImage('|', small_font, r=255, g=255, b=0) - img.paste(symbol1_timage, (x_offset + 5, 7)) - golf_standings1_timage = self.textImage(each_player, small_font, r=255, g=255, b=255) - img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 7)) - x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7) - - for each_player2 in golf_standings2: - symbol2_timage = self.textImage('|', small_font, r=255, g=255, b=0) - img.paste(symbol2_timage, (x_offset2 + 5, 20)) - golf_standings2_timage = self.textImage(each_player2, small_font, r=255, g=255, b=255) - img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 20)) - x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7) - - if x_offset >= x_offset2: - x_offset += buff_size - else: - x_offset = x_offset2 - x_offset += buff_size - else: - strHomeTeam = match['home_team'] - strAwayTeam = match['away_team'] - - if time != 'future': - intHomeScore = str(match['home_score']) - intAwayScore = str(match['away_score']) - - try: - - home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strHomeTeam]['logo'])) - - except Exception as e: - home_logo = self.textImage(strHomeTeam.replace(' ', '\n'), extra_small_font, r = 255, g = 255, b = 255) - - try: - - away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strAwayTeam]['logo'])) - - except Exception as e: - away_logo = self.textImage(strAwayTeam.replace(' ', '\n'), extra_small_font, r = 255, g = 255, b = 255) - - img.paste(away_logo, (x_offset,0)) - - x_offset += away_logo.size[0] + 4 - - if time == 'future': - #img.paste(date_timage, (x_offset+5, 0)) - - try: - h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', '')) - except: - pass - try: - a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', '')) - except: - pass - vs_timage = self.textImage('vs', med_font, r = 255, g = 255, b = 255, h_buff = 5) - try: - hc_timage = self.textImage(sports_info[strHomeTeam]['code'], med_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) - except Exception as e: - hc_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255) - try: - ac_timage = self.textImage(sports_info[strAwayTeam]['code'], med_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) - except Exception as e: - ac_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255) - - vs_size = vs_timage.size[0] + ac_timage.size[0] + hc_timage.size[0] - - main_offset = 5 + x_offset + int(max(vs_size, date_timage.size[0])/2) - - img.paste(date_timage, (main_offset - int(date_timage.size[0]/2), 0)) - img.paste(vs_timage, (main_offset - int(vs_timage.size[0]/2),9)) - img.paste(ac_timage, (main_offset - int(vs_timage.size[0]/2) - ac_timage.size[0], 9)) - img.paste(hc_timage, (main_offset + int(vs_timage.size[0]/2),9)) - x_offset = (main_offset + max(int(date_timage.size[0]/2), int(vs_timage.size[0]/2) + hc_timage.size[0]) + 6) - else: - score_image = self.textImage(intAwayScore + '-' + intHomeScore, large_font, h_buff = 5, r = 255, g = 255, b = 255) - try: - h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', '')) - except: - pass - try: - a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', '')) - except: - pass - try: - hc_timage = self.textImage(sports_info[strHomeTeam]['code'], small_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) - except Exception as e: - hc_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255) - try: - ac_timage = self.textImage(sports_info[strAwayTeam]['code'], small_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) - except Exception as e: - ac_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255) - - vs_timage = self.textImage('VS', extra_small_font, r = 255, g = 255, b = 255) - - vs_size = hc_timage.size[0] + ac_timage.size[0] + vs_timage.size[0] - - main_offset = x_offset + int(max(vs_size, date_timage.size[0], score_image.size[0])/2) - img.paste(date_timage,(main_offset - int(date_timage.size[0]/2),0)) - img.paste(vs_timage,(main_offset - int(vs_timage.size[0]/2),10)) - img.paste(ac_timage, (main_offset - int(vs_timage.size[0]/2) - ac_timage.size[0], 9)) - img.paste(score_image, (main_offset - int(score_image.size[0]/2), 15)) - if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore): - ua_image = Image.new("RGB", (ac_timage.size[0] -2, 1)) - ua_image1 = ImageDraw.Draw(ua_image) - ua_image1.line((0,0,ac_timage.size[0]-2,0), fill="red", width = 0) - img.paste(ua_image, (main_offset - int(vs_timage.size[0]/2)-ac_timage.size[0], ac_timage.size[1]+7)) - img.paste(hc_timage, (main_offset + int(vs_timage.size[0]/2),9)) - if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore): - u_image = Image.new("RGB", (hc_timage.size[0] -2, 1)) - u_image1 = ImageDraw.Draw(u_image) - u_image1.line((0,0,hc_timage.size[0]-2,0), fill="red", width = 0) - img.paste(u_image, (main_offset + int(vs_timage.size[0]/2), hc_timage.size[1]+7)) - x_offset = (main_offset + max(int(date_timage.size[0]/2), int(vs_timage.size[0]/2) + hc_timage.size[0], int(score_image.size[0]/2)) + 4) - - img.paste(home_logo, (x_offset,0)) - - x_offset += home_logo.size[0] - x_offset += buff_size img = img.crop((0,0,x_offset ,32)) imgs.append(img) - - - except Exception as e: pass # logf = open('log.txt', "a") @@ -2416,9 +3187,6 @@ class StockTicker(): # logf.write('. type: ' + str(exc_type)) # logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) # logf.close() - - - return self.stitchImage(imgs) @@ -2848,7 +3616,7 @@ class StockTicker(): width, height = league_logo.size league_logo2 = league_logo.resize((int(width/2), int(height/2))) - if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'): + if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'): x_offset += 10 else: img.paste(league_logo2, (x_offset,0)) @@ -2867,238 +3635,378 @@ class StockTicker(): buff_size = 20 + if league == 'UFC': + try: + date_img = self.textImage(league_info[0]['date'], small_font, r=0,g=150,b=255) + eventname_img = self.textImage(league_info[0]['name'].upper(), font, r=255, g=0, b=0) + venue_img = self.textImage(league_info[0]['venue'], small_font, r=255, g=255, b=0) + city_img = self.textImage(league_info[0]['city'], small_font, r=255, g=255, b=255) + try: + country_img = self.textImage(league_info[0]['country'], small_font, r=255, g=128, b=0) + except: + pass + broadcast_img = self.textImage(league_info[0]['broadcast'], small_font, r=255, g=0, b=0) + time_img = self.textImage(league_info[0]['time'], small_font, r =0, g=150, b=255) - for match in league_info: + try: + img.paste(country_img, (x_offset + eventname_img.size[0] + 2, 2)) + except: + country_img = 0 + pass + img.paste(eventname_img, (x_offset, 0)) + img.paste(city_img, (x_offset + date_img.size[0] + 3 + time_img.size[0] + 3 + broadcast_img.size[0] + 7 + venue_img.size[0] + 3, 10)) + img.paste(venue_img, (x_offset + date_img.size[0] + 3 + time_img.size[0] + 3 + broadcast_img.size[0] + 7,10)) + img.paste(broadcast_img, (x_offset + date_img.size[0] + 3 + time_img.size[0] + 3, 10)) + img.paste(date_img, (x_offset, 10)) + img.paste(time_img, (x_offset + date_img.size[0] + 3, 10)) + try: + x_offset = 10 + max(x_offset + eventname_img.size[0] + 2 + country_img.size[0], x_offset + date_img.size[0] + 3 + time_img.size[0] + 3 + broadcast_img.size[0] + 7 + venue_img.size[0] + 3 + city_img.size[0]) + except: + x_offset = 10 + max(x_offset + eventname_img.size[0], x_offset + date_img.size[0] + 3 + time_img.size[0] + 3 + broadcast_img.size[0] + 7 + venue_img.size[0] + 3 + city_img.size[0]) - dateEvent = match['date'].replace('-', '.') - date_timage = self.textImage(dateEvent, small_font, r = 255, g = 255, b = 255) + for fight in league_info[0]['fights']: + try: + if time != 'past': + fighter1_img = Image.open('logos/ufc/{}.png'.format(fight['fighter1id'])) + elif time == 'past': + fighter1_img = Image.open('logos/ufc_past/{}.png'.format(fight['fighter1id'])) + fighter1_img.thumbnail((9000,16)) + except: + fighter1_img = Image.open('logos/unknown.png') + fighter1_img.thumbnail((9000,16)) + pass - if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'): - event = match['event'] - venue = match['venue'] - city = match['city'] - country = match['country'] - season = match['season'] + draw = ImageDraw.Draw(img, "RGBA") + name1_img = self.textImage(fight['fighter1name'].split(' ',1)[0][0] + '.' + fight['fighter1name'].split(' ',1)[1], small_font, r=255,g=255,b=255) + max_fighter1pic = max(name1_img.size[0],fighter1_img.size[0]) - if time != 'future': - golf_standings1 = match['golf_standings'][::2] - golf_standings2 = match['golf_standings'][1::2] - img.paste(league_logo2, (x_offset, 0)) - x_offset += league_logo2.size[0] + 5 + img.paste(fighter1_img, (x_offset + int(max_fighter1pic/2) - int(fighter1_img.size[0]/2), 0), mask=fighter1_img) + draw.rectangle([(x_offset,16),(x_offset + name1_img.size[0]-4,10)], fill=(5,5,5,200)) + draw.text((x_offset + int(max_fighter1pic/2) - int(name1_img.size[0]/2),10), fight['fighter1name'].split(' ',1)[0][0] + '.' + fight['fighter1name'].split(' ',1)[1], fill=(255,255,255),font=small_font) + try: + country1_img = Image.open('logos/ufc_countries/{}'.format(fight['fighter1country'].split('/')[-1].split('&')[0])) + country1_img.thumbnail((9000,8)) + img.paste(country1_img,(x_offset, 0)) + except: + pass + x_offset += max_fighter1pic + try: + if time != 'past': + fighter2_img = Image.open('logos/ufc/{}.png'.format(fight['fighter2id'])) + elif time == 'past': + fighter2_img = Image.open('logos/ufc_past/{}.png'.format(fight['fighter2id'])) + fighter2_img.thumbnail((9000,16)) + except: + fighter2_img = Image.open('logos/unknown.png') + fighter2_img.thumbnail((9000,16)) + pass + weight_img = self.textImage(fight['weight_div'].upper(), small_font, r=255,g=0,b=0) + vs_img = self.textImage('VS', small_font, r=255,g=255,b=255) + + if time != 'past': + odds1_img = self.textImage(fight['fighter1odds'], small_font, r=0, g=255, b=0) + odds2_img = self.textImage(fight['fighter2odds'], small_font, r=0, g=255, b=0) + max_middle = max(vs_img.size[0] + odds1_img.size[0] + odds2_img.size[0], weight_img.size[0]) + img.paste(weight_img, (x_offset + int(max_middle/2) - int(weight_img.size[0]/2), 1)) + img.paste(odds1_img, (x_offset + int(max_middle/2) - int(vs_img.size[0]/2) - odds1_img.size[0],8)) + img.paste(vs_img, (x_offset + int(max_middle/2) - int(vs_img.size[0]/2),8)) + img.paste(odds2_img, (x_offset + int(max_middle/2) + int(vs_img.size[0]/2),8)) + elif time == 'past': + if fight['fighter1win']: + win1_img = self.textImage('WIN', small_font, r=0, g=255, b=0) + win2_img = self.textImage('LOSS', small_font, r=255, g=0, b=0) + elif not fight['fighter1win'] and not fight['fighter2win']: + win1_img = self.textImage('DRAW', small_font, r=80, g=80, b=80) + win2_img = self.textImage('DRAW', small_font, r=80, g=80, b=80) + else: + win1_img = self.textImage('LOSS', small_font, r=255, g=0, b=0) + win2_img = self.textImage('WIN', small_font, r=0, g=255, b=0) + max_middle = max(vs_img.size[0] + win1_img.size[0] + win2_img.size[0], weight_img.size[0]) + img.paste(weight_img, (x_offset + int(max_middle/2) - int(weight_img.size[0]/2), 1)) + img.paste(win1_img, (x_offset + int(max_middle/2) - int(vs_img.size[0]/2) - int(win1_img.size[0]),8)) + img.paste(vs_img, (x_offset + int(max_middle/2) - int(vs_img.size[0]/2),8)) + img.paste(win2_img, (x_offset + int(max_middle/2) + int(vs_img.size[0]/2),8)) + x_offset += max_middle + + name2_img = self.textImage(fight['fighter2name'].split(' ',1)[0][0] + '.' + fight['fighter2name'].split(' ',1)[1], small_font, r=255,g=255,b=255) + max_fighter2pic = max(name2_img.size[0],fighter2_img.size[0]) + + img.paste(fighter2_img, (x_offset + int(max_fighter2pic/2) - int(fighter2_img.size[0]/2), 0), mask=fighter2_img) + draw.rectangle([(x_offset,16),(x_offset + name2_img.size[0]-4,10)], fill=(5,5,5,200)) + draw.text((x_offset + int(max_fighter2pic/2) - int(name2_img.size[0]/2),10), fight['fighter2name'].split(' ',1)[0][0] + '.' + fight['fighter2name'].split(' ',1)[1], fill=(255,255,255),font=small_font) + + try: + country2_img = Image.open('logos/ufc_countries/{}'.format(fight['fighter2country'].split('/')[-1].split('&')[0])) + country2_img.thumbnail((9000,8)) + img.paste(country2_img,(x_offset + max_fighter2pic - country2_img.size[0] - 2, 0)) + except: + pass + + x_offset += max_fighter2pic + 15 + + except: + pass + + # DONT FORGET TO CHANGE DIRECTORY FOR PAST UFC GAMES + + else: + + for match in league_info: + try: + dateEvent = match['date2'] + except: + dateEvent = match['date'].replace('-', '.') if time == 'future': - - event_timage = self.textImage(event, small_font, r=255, g=255, b=0) - venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0) - city_timage = self.textImage(city, small_font, r=255, g=255, b=255) - country_timage = self.textImage(country, small_font, r=255, g=255, b=255) - season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255) - season_timage = self.textImage(season, small_font, r=255, g=255, b=255) - date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171) - - #event - img.paste(event_timage, (x_offset, 1)) - #venue - img.paste(venue_timage,(x_offset, 9)) - x_offset += (max(event_timage.size[0], venue_timage.size[0]) + 5) - #date - img.paste(date1_timage, (x_offset, 1)) - img.paste(date_timage, (x_offset + date1_timage.size[0] + 2, 1)) - #city - img.paste(city_timage,(x_offset, 9)) - #country - img.paste(country_timage,(x_offset + city_timage.size[0] + 7,9)) - #season - img.paste(season1_timage,(x_offset + date1_timage.size[0] + 2 + date_timage.size[0] + 5,1)) - img.paste(season_timage,(x_offset + date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5,1)) - - x_offset += max(date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5 + season_timage.size[0], city_timage.size[0] + 7 + country_timage.size[0]) - x_offset += (buff_size - 10) + try: + date_timage = self.textImage(dateEvent + ' ' + match['time'].replace("EST","").replace('PM','P').replace('AM','A').replace('CET',''), small_font, r = 255, g = 255, b = 255) + except: + date_timage = self.textImage(dateEvent, small_font, r = 255, g = 255, b = 255) else: - event_timage = self.textImage(event, small_font, r=255, g=255, b=0) - venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0) - city_timage = self.textImage(city, small_font, r=255, g=255, b=255) - country_timage = self.textImage(country, small_font, r=255, g=255, b=255) - season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255) - season_timage = self.textImage(season, small_font, r=255, g=255, b=255) - date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171) + date_timage = self.textImage(dateEvent, small_font, r = 255, g = 255, b = 255) - #event - img.paste(event_timage, (x_offset, 1)) - #venue - img.paste(venue_timage,(x_offset, 9)) - x_offset += (max(event_timage.size[0], venue_timage.size[0]) + 5) - #date - img.paste(date1_timage, (x_offset, 1)) - img.paste(date_timage, (x_offset + date1_timage.size[0] + 2, 1)) - #city - img.paste(city_timage,(x_offset, 9)) - #country - img.paste(country_timage,(x_offset + city_timage.size[0] + 7,9)) - #season - img.paste(season1_timage,(x_offset + date1_timage.size[0] + 2 + date_timage.size[0] + 5,1)) - img.paste(season_timage,(x_offset + date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5,1)) - - x_offset += max(date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5 + season_timage.size[0], city_timage.size[0] + 7 + country_timage.size[0]) - x_offset2 = x_offset + if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'): + event = match['event'] + venue = match['venue'] + city = match['city'] + country = match['country'] + season = match['season'] - for each_player in golf_standings1: - symbol1_timage = self.textImage('|', small_font, r=255, g=255, b=0) - img.paste(symbol1_timage, (x_offset + 5, 1)) - golf_standings1_timage = self.textImage(each_player, small_font, r=255, g=255, b=255) - img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 1)) - x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7) + if (time != 'future') and (league != 'LIV'): + golf_standings1 = match['golf_standings'][::2] + golf_standings2 = match['golf_standings'][1::2] + elif (time!= 'future') and (league == 'LIV'): + golf_standings1 = match['golf_standings'][0][::2] + golf_standings2 = match['golf_standings'][0][1::2] + golf_standings1_teams = match['golf_standings'][1][::2] + golf_standings2_teams = match['golf_standings'][1][1::2] - for each_player2 in golf_standings2: - symbol2_timage = self.textImage('|', small_font, r=255, g=255, b=0) - img.paste(symbol2_timage, (x_offset2 + 5, 9)) - golf_standings2_timage = self.textImage(each_player2, small_font, r=255, g=255, b=255) - img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 9)) - x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7) + img.paste(league_logo2, (x_offset, 0)) + x_offset += league_logo2.size[0] + 5 - if x_offset >= x_offset2: + if time == 'future': + + event_timage = self.textImage(event, small_font, r=255, g=255, b=0) + venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0) + city_timage = self.textImage(city, small_font, r=255, g=255, b=255) + country_timage = self.textImage(country, small_font, r=255, g=255, b=255) + season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255) + season_timage = self.textImage(season, small_font, r=255, g=255, b=255) + date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171) + + #event + img.paste(event_timage, (x_offset, 1)) + #venue + img.paste(venue_timage,(x_offset, 9)) + x_offset += (max(event_timage.size[0], venue_timage.size[0]) + 5) + #date + img.paste(date1_timage, (x_offset, 1)) + img.paste(date_timage, (x_offset + date1_timage.size[0] + 2, 1)) + #city + img.paste(city_timage,(x_offset, 9)) + #country + img.paste(country_timage,(x_offset + city_timage.size[0] + 7,9)) + #season + img.paste(season1_timage,(x_offset + date1_timage.size[0] + 2 + date_timage.size[0] + 5,1)) + img.paste(season_timage,(x_offset + date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5,1)) + + x_offset += max(date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5 + season_timage.size[0], city_timage.size[0] + 7 + country_timage.size[0]) x_offset += (buff_size - 10) else: - x_offset = x_offset2 - x_offset += (buff_size - 10) + event_timage = self.textImage(event, small_font, r=255, g=255, b=0) + venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0) + city_timage = self.textImage(city, small_font, r=255, g=255, b=255) + country_timage = self.textImage(country, small_font, r=255, g=255, b=255) + season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255) + season_timage = self.textImage(season, small_font, r=255, g=255, b=255) + date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171) - else: - strHomeTeam = match['home_team'] - strAwayTeam = match['away_team'] - - if time != 'future': - intHomeScore = str(match['home_score']) - intAwayScore = str(match['away_score']) - - try: - - home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strHomeTeam]['logo'])) - width1, height1 = home_logo.size - home_logo1 = home_logo.resize((int(width1/2), int(height1/2))) - except Exception as e: - home_logo1 = self.textImage(strHomeTeam, small_font, r = 255, g = 255, b = 255) - + #event + img.paste(event_timage, (x_offset, 1)) + #venue + img.paste(venue_timage,(x_offset, 9)) + x_offset += (max(event_timage.size[0], venue_timage.size[0]) + 5) + #date + img.paste(date1_timage, (x_offset, 1)) + img.paste(date_timage, (x_offset + date1_timage.size[0] + 2, 1)) + #city + img.paste(city_timage,(x_offset, 9)) + #country + img.paste(country_timage,(x_offset + city_timage.size[0] + 7,9)) + #season + img.paste(season1_timage,(x_offset + date1_timage.size[0] + 2 + date_timage.size[0] + 5,1)) + img.paste(season_timage,(x_offset + date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5,1)) - try: - - away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strAwayTeam]['logo'])) - width2, height2 = away_logo.size - away_logo1 = away_logo.resize((int(width2/2), int(height2/2))) - except Exception as e: - away_logo1 = self.textImage(strAwayTeam, small_font, r = 255, g = 255, b = 255) + x_offset += max(date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5 + season_timage.size[0], city_timage.size[0] + 7 + country_timage.size[0]) + x_offset2 = x_offset - error = False + for each_player in golf_standings1: + symbol1_timage = self.textImage('|', small_font, r=255, g=255, b=0) + img.paste(symbol1_timage, (x_offset + 5, 1)) + golf_standings1_timage = self.textImage(each_player, small_font, r=255, g=255, b=255) + img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 1)) + x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7) - img.paste(away_logo1, (x_offset,0)) - x_offset += (away_logo1.size[0] + 2) + for each_player2 in golf_standings2: + symbol2_timage = self.textImage('|', small_font, r=255, g=255, b=0) + img.paste(symbol2_timage, (x_offset2 + 5, 9)) + golf_standings2_timage = self.textImage(each_player2, small_font, r=255, g=255, b=255) + img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 9)) + x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7) + if league == 'LIV': + if x_offset >= x_offset2: + x_offset += 5 + x_offset2 = x_offset + else: + x_offset2 += 5 + x_offset = x_offset2 - if time == 'future': - try: - h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', '')) - except: - pass - try: - a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', '')) - except: - pass - try: - hc_timage = self.textImage(sports_info[strHomeTeam]['code'], font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) - except: - hc_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255) - error = True - try: - ac_timage = self.textImage(sports_info[strAwayTeam]['code'], font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) - except: - ac_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255) - error = True + for each_team in golf_standings1_teams: + symbol1_timage = self.textImage('|', small_font, r=0, g=255, b=0) + img.paste(symbol1_timage, (x_offset + 5, 1)) + golf_standings1_timage = self.textImage(each_team, small_font, r=255, g=255, b=255) + img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 1)) + x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7) + for each_team2 in golf_standings2_teams: + symbol2_timage = self.textImage('|', small_font, r=0, g=255, b=0) + img.paste(symbol2_timage, (x_offset2 + 5, 9)) + golf_standings2_timage = self.textImage(each_team2, small_font, r=255, g=255, b=255) + img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 9)) + x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7) + + if x_offset >= x_offset2: + x_offset += (buff_size - 10) + else: + x_offset = x_offset2 + x_offset += (buff_size - 10) - vs_timage = self.textImage('vs', font, r = 255, g = 255, b = 255, h_buff = 5) - x_offsetdate2 = x_offset + int((hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0])/2)- int(date_timage.size[0]/2) - img.paste(date_timage, (x_offsetdate2,0)) - x_offsetdate2 += date_timage.size[0] - img.paste(ac_timage, (x_offset, 5)) - x_offset += ac_timage.size[0] - img.paste(vs_timage, (x_offset, 5)) - x_offset += vs_timage.size[0] - img.paste(hc_timage, (x_offset, 5)) - x_offset += hc_timage.size[0] - #x_offset += max(date_timage.size[0], (hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0])) else: - score_image = self.textImage(intAwayScore + '-' + intHomeScore, font, h_buff = 5, r = 255, g = 255, b = 255) - try: - h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', '')) - except: - pass - try: - a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', '')) - except: - pass + strHomeTeam = match['home_team'] + strAwayTeam = match['away_team'] + + if time != 'future': + intHomeScore = str(match['home_score']) + intAwayScore = str(match['away_score']) try: - hc_timage = self.textImage(sports_info[strHomeTeam]['code'], font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) - except: - hc_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255) - error = True + home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strHomeTeam]['logo'])) + width1, height1 = home_logo.size + home_logo1 = home_logo.resize((int(width1/2), int(height1/2))) + except Exception as e: + home_logo1 = self.textImage(strHomeTeam, small_font, r = 255, g = 255, b = 255) + try: - ac_timage = self.textImage(sports_info[strAwayTeam]['code'], font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) - except: - ac_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255) - error = True + away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strAwayTeam]['logo'])) + width2, height2 = away_logo.size + away_logo1 = away_logo.resize((int(width2/2), int(height2/2))) + except Exception as e: + away_logo1 = self.textImage(strAwayTeam, small_font, r = 255, g = 255, b = 255) - x_offsetdate2 = x_offset + ac_timage.size[0] + int(score_image.size[0]/2)- int(date_timage.size[0]/2) - img.paste(date_timage, (x_offsetdate2,0)) - x_offsetdate2 += date_timage.size[0] - #img.paste(date_timage, (x_offset+20+int((score_image.size[0] - date_timage.size[0])/2),0)) - img.paste(ac_timage, (x_offset, 5)) - if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore): - ua_image = Image.new("RGB", (ac_timage.size[0] -3, 1)) - ua_image1 = ImageDraw.Draw(ua_image) - ua_image1.line((0,0,ac_timage.size[0]-3,0), fill="red", width = 0) - img.paste(ua_image, (x_offset, ac_timage.size[1]+4)) - x_offset += ac_timage.size[0] - img.paste(score_image, (x_offset, 5)) - x_offset += score_image.size[0] - img.paste(hc_timage, (x_offset, 5)) - if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore): - u_image = Image.new("RGB", (hc_timage.size[0] -3, 1)) - u_image1 = ImageDraw.Draw(u_image) - u_image1.line((0,0,hc_timage.size[0]-3,0), fill="red", width = 0) - img.paste(u_image, (x_offset, hc_timage.size[1]+4)) - x_offset += hc_timage.size[0] + error = False - # if date_timage.size[0] > score_image.size[0]: - # img.paste(date_timage, (x_offset+2, 0)) - # img.paste(hc_timage, (x_offset+6, 5)) - # img.paste(vs_timage, (x_offset+5 + hc_timage.size[0], 5)) - # img.paste(ac_timage, (x_offset+6 + hc_timage.size[0] + vs_timage.size[0], 5)) - # img.paste(score_image, (x_offset + 2 + int((date_timage.size[0] - score_image.size[0])/2), 5)) - # else: - - # img.paste(date_timage, (x_offset+1+int((score_image.size[0] - date_timage.size[0] )/2), 0)) - # vs_size = hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0] - # img.paste(hc_timage, (x_offset + 1 + int((score_image.size[0] - vs_size)/2), 5)) - # img.paste(vs_timage, (x_offset + int((score_image.size[0] - vs_size)/2) + hc_timage.size[0], 5)) - # img.paste(ac_timage, (x_offset+1 + int((score_image.size[0] - vs_size)/2) + hc_timage.size[0] + vs_timage.size[0], 5)) - # img.paste(score_image, (x_offset+1, 5)) + img.paste(away_logo1, (x_offset,0)) + x_offset += (away_logo1.size[0] + 2) - # x_offset += max( date_timage.size[0]+4, hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0]+4, 2 + int(score_image.size[0])) - if error: - img.paste(home_logo1, (max(x_offset + date_timage.size[0], x_offsetdate2),0)) - x_offset += (home_logo1.size[0] + date_timage.size[0]) - else: - img.paste(home_logo1, (max(x_offset, x_offsetdate2),0)) - x_offset += home_logo1.size[0] - x_offset += buff_size - x_offset += 20 + if time == 'future': + try: + h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', '')) + except: + pass + try: + a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', '')) + except: + pass + try: + hc_timage = self.textImage(sports_info[strHomeTeam]['code'], font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) + except: + hc_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255) + error = True + try: + ac_timage = self.textImage(sports_info[strAwayTeam]['code'], font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) + except: + ac_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255) + error = True + + vs_timage = self.textImage('vs', font, r = 255, g = 255, b = 255, h_buff = 5) + x_offsetdate2 = x_offset + int((hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0])/2)- int(date_timage.size[0]/2) + + if date_timage.size[0] > (ac_timage.size[0] + vs_timage.size[0] + hc_timage.size[0]): + x_offset3 = x_offset + int(date_timage.size[0]/2) + img.paste(date_timage, (x_offset,0)) + x_offset += date_timage.size[0] + img.paste(ac_timage, (x_offset3 - int(ac_timage.size[0]) - int(vs_timage.size[0]/2), 5)) + img.paste(vs_timage, (x_offset3 - int(vs_timage.size[0]/2), 5)) + img.paste(hc_timage, (x_offset3 + int(vs_timage.size[0]/2), 5)) + else: + img.paste(date_timage, (x_offsetdate2,0)) + x_offsetdate2 += date_timage.size[0] + img.paste(ac_timage, (x_offset, 5)) + x_offset += ac_timage.size[0] + img.paste(vs_timage, (x_offset, 5)) + x_offset += vs_timage.size[0] + img.paste(hc_timage, (x_offset, 5)) + x_offset += hc_timage.size[0] + + else: + score_image = self.textImage(intAwayScore + '-' + intHomeScore, font, h_buff = 5, r = 255, g = 255, b = 255) + try: + h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', '')) + except: + pass + try: + a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', '')) + except: + pass + + try: + hc_timage = self.textImage(sports_info[strHomeTeam]['code'], font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) + except: + hc_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255) + error = True + try: + ac_timage = self.textImage(sports_info[strAwayTeam]['code'], font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) + except: + ac_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255) + error = True + + x_offsetdate2 = x_offset + ac_timage.size[0] + int(score_image.size[0]/2)- int(date_timage.size[0]/2) + img.paste(date_timage, (x_offsetdate2,0)) + x_offsetdate2 += date_timage.size[0] + #img.paste(date_timage, (x_offset+20+int((score_image.size[0] - date_timage.size[0])/2),0)) + img.paste(ac_timage, (x_offset, 5)) + if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore): + ua_image = Image.new("RGB", (ac_timage.size[0] -3, 1)) + ua_image1 = ImageDraw.Draw(ua_image) + ua_image1.line((0,0,ac_timage.size[0]-3,0), fill="red", width = 0) + img.paste(ua_image, (x_offset, ac_timage.size[1]+4)) + x_offset += ac_timage.size[0] + img.paste(score_image, (x_offset, 5)) + x_offset += score_image.size[0] + img.paste(hc_timage, (x_offset, 5)) + if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore): + u_image = Image.new("RGB", (hc_timage.size[0] -3, 1)) + u_image1 = ImageDraw.Draw(u_image) + u_image1.line((0,0,hc_timage.size[0]-3,0), fill="red", width = 0) + img.paste(u_image, (x_offset, hc_timage.size[1]+4)) + x_offset += hc_timage.size[0] + + if error: + img.paste(home_logo1, (max(x_offset + date_timage.size[0], x_offsetdate2),0)) + x_offset += (home_logo1.size[0] + date_timage.size[0]) + else: + img.paste(home_logo1, (max(x_offset, x_offsetdate2),0)) + x_offset += home_logo1.size[0] + x_offset += buff_size + + x_offset += 20 #INDENT THIS OR NO? img = img.crop((0,0,x_offset ,16)) imgs.append(img) except: pass - return self.stitchImage(imgs) @@ -3552,15 +4460,13 @@ class StockTicker(): f = open('csv/daily_weather.json', 'r') all_settings = json.load(f) f.close() - - + if all_settings['title']: title_img = self.openImage('feature_titles/forecast.png') imgs = [title_img, self.blank] else: imgs = [] - - + f = open('csv/daily_weather.json', 'r') daily_weathers = json.load(f) f.close() @@ -3569,16 +4475,14 @@ class StockTicker(): for i, location in enumerate(locations): try: img = Image.new('RGB', (1000, 32)) - - + daily_weather = daily_weathers['locations'][location] small_font = ImageFont.load("./fonts/5x7.pil") extra_small_font = ImageFont.load("./fonts/4x6.pil") large_font = ImageFont.load("./fonts/10x20.pil") - - - location_img = self.textImage(location.upper(), extra_small_font, r = 255, g = 255, b = 0) + + location_img = self.textImage(location.upper(), small_font, r = 255, g = 255, b = 0) main = daily_weather[0]['main_weather'] if main == 'Clouds': main = daily_weather[0]['description'] @@ -3593,15 +4497,11 @@ class StockTicker(): weather_dir = './logos/weather_icons' weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png') - - + temp = self.convertTemp(daily_weather[0]['temp'], daily_weathers['temp']) min_temp = self.convertTemp(daily_weather[0]['min_temp'], daily_weathers['temp']) max_temp = self.convertTemp(daily_weather[0]['max_temp'], daily_weathers['temp']) - - - - + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) deg_img = self.textImage('o', small_font) @@ -3616,39 +4516,35 @@ class StockTicker(): month = months[int(datetime.now().strftime('%m'))-1] date = str(int(datetime.now().strftime('%d'))) weekday = weekdays[datetime.today().weekday()] - date_img = self.textImage((month + ' ' + date + ',' + weekday).upper(), extra_small_font) - - - rain_img = Image.open(weather_dir + '/rain-chance.png') - rtext_img = self.textImage(str(int(daily_weather[0]['rain_chance']*100)) + '%', extra_small_font) - hum_img = Image.open(weather_dir + '/humidity.png') - htext_img = self.textImage(str(daily_weather[0]['humidity']) + '%', extra_small_font) - wind_img = Image.open(weather_dir + '/wind.png') - wtext_img = self.textImage(str(daily_weather[0]['wind_speed']) + 'm/s'.upper(), extra_small_font) - uv_img = Image.open(weather_dir + '/uv.png') - utext_img = self.textImage(str(round(daily_weather[0]['uv'], 1)) , small_font) - cloud_img = Image.open(weather_dir + '/clouds.png') - ctext_img = self.textImage(str(daily_weather[0]['clouds']) + '%', small_font) - wind_img = Image.open(weather_dir + '/wind.png') - - - w_speed = daily_weather[0]['wind_speed']*3.6 - w_unit = 'K/H' - if daily_weathers['wind_speed'] == "miles/hour": - w_speed = daily_weather[0]['wind_speed']*2.236936 - w_unit = 'M/H' - - - wtext_img = self.textImage("{0:.0f}".format(w_speed) + w_unit, small_font) - wdir_img = self.textImage(self.degreesToCompass(daily_weather[0]['wind_direction']), small_font) - vis_img = Image.open(weather_dir + '/visibility.png') - vtext_img = self.textImage(str(round(daily_weather[0]['visibility']/1000, 1)) + 'km'.upper(), small_font) - - + date_img = self.textImage((month + ' ' + date + ',' + weekday).upper(), small_font) + + if daily_weathers['current_weather']: + rain_img = Image.open(weather_dir + '/rain-chance.png') + rtext_img = self.textImage(str(int(daily_weather[0]['rain_chance']*100)) + '%', small_font) + hum_img = Image.open(weather_dir + '/humidity.png') + htext_img = self.textImage(str(daily_weather[0]['humidity']) + '%', small_font) + wind_img = Image.open(weather_dir + '/wind.png') + wtext_img = self.textImage(str(daily_weather[0]['wind_speed']) + 'm/s'.upper(), small_font) + uv_img = Image.open(weather_dir + '/uv.png') + utext_img = self.textImage(str(round(daily_weather[0]['uv'], 1)) , small_font) + cloud_img = Image.open(weather_dir + '/clouds.png') + ctext_img = self.textImage(str(daily_weather[0]['clouds']) + '%', small_font) + wind_img = Image.open(weather_dir + '/wind.png') + + w_speed = daily_weather[0]['wind_speed']*3.6 + w_unit = 'K/H' + if daily_weathers['wind_speed'] == "miles/hour": + w_speed = daily_weather[0]['wind_speed']*2.236936 + w_unit = 'M/H' + + wtext_img = self.textImage("{0:.0f}".format(w_speed) + w_unit, small_font) + wdir_img = self.textImage(self.degreesToCompass(daily_weather[0]['wind_direction']), small_font) + vis_img = Image.open(weather_dir + '/visibility.png') + vtext_img = self.textImage(str(round(daily_weather[0]['visibility']/1000, 1)) + 'km'.upper(), small_font) + img.paste(location_img, (0,0)) - x_offset = location_img.size[0]+2 - + x_offset2 = location_img.size[0]+5 img.paste(weather_img, (5,9)) x_offset = 5 + weather_img.size[0] + 1 @@ -3659,79 +4555,66 @@ class StockTicker(): img.paste(deg_img, (x_offset + main_img.size[0]//2 - temp_img.size[0]//2 + temp_img.size[0], 8)) x_offset += max( main_img.size[0], temp_img.size[0] + deg_img.size[0]) - - + img.paste(min_img, (x_offset - 0, 12)) img.paste(max_img, (x_offset - 0, 21)) x_offset += max(min_img.size[0], max_img.size[0]) + 2 - img.paste(date_img, (x_offset, 1)) - x_offset += date_img.size[0]+2 + img.paste(date_img, (x_offset2, 0)) + x_offset2 += date_img.size[0]+5 - img.paste(rain_img, (x_offset,0)) - x_offset += rain_img.size[0]+2 - img.paste(rtext_img, (x_offset, 1)) - x_offset += rtext_img.size[0]+2 + if daily_weathers['current_weather']: + img.paste(rain_img, (x_offset2,0)) + x_offset2 += rain_img.size[0]+2 + img.paste(rtext_img, (x_offset2,1)) + x_offset2 += rtext_img.size[0]+2 + + img.paste(hum_img, (x_offset2, 0)) + x_offset2 += hum_img.size[0]+2 + img.paste(htext_img, (x_offset2, 1)) + x_offset2+= htext_img.size[0]+2 + + img.paste(uv_img, ( x_offset2, 0)) + x_offset2 += uv_img.size[0]+2 + img.paste(utext_img, (x_offset2, 1)) + x_offset2 += utext_img.size[0]+2 + + img.paste(cloud_img, (x_offset2,0)) + x_offset2 += cloud_img.size[0]+2 + img.paste(ctext_img, (x_offset2, 1)) + x_offset2 += ctext_img.size[0]+2 + + img.paste(wind_img, (x_offset2,0)) + x_offset2 += wind_img.size[0]+2 + img.paste(wtext_img, (x_offset2, 1)) + x_offset2 += wtext_img.size[0]+2 + img.paste(wdir_img, (x_offset2, 1)) + x_offset2+= wdir_img.size[0]+2 + + img.paste(vis_img, (x_offset2,-1)) + x_offset2+= vis_img.size[0]+2 + img.paste(vtext_img, (x_offset2, 1)) + x_offset2 += vtext_img.size[0] +2 - img.paste(hum_img, (x_offset, 0)) - x_offset += hum_img.size[0]+2 - img.paste(htext_img, (x_offset, 1)) - x_offset+= htext_img.size[0]+2 - - img.paste(uv_img, ( x_offset, 0)) - x_offset += uv_img.size[0]+2 - img.paste(utext_img, (x_offset, 1)) - x_offset += utext_img.size[0]+2 - - img.paste(cloud_img, (x_offset,0)) - x_offset += cloud_img.size[0]+2 - img.paste(ctext_img, (x_offset, 1)) - x_offset += ctext_img.size[0]+2 - - img.paste(wind_img, (x_offset,0)) - x_offset += wind_img.size[0]+2 - img.paste(wtext_img, (x_offset, 1)) - x_offset += wtext_img.size[0]+2 - img.paste(wdir_img, (x_offset, 1)) - x_offset+= wdir_img.size[0]+2 - - img.paste(vis_img, (x_offset,0)) - x_offset+= vis_img.size[0]+2 - img.paste(vtext_img, (x_offset, 1)) - x_offset += vtext_img.size[0] +2 - - crop_x = x_offset - #img.paste(uv_img, ( 96, 0)) - #img.paste(utext_img, (109, 0)) - #img.paste(wind_img, (96,0)) - #img.paste(wtext_img, (109,0)) - #img.paste(date_img, (70, 0)) - x_offset = 77 - for i in range(1,len(daily_weather)): weekday = weekdays[(datetime.today().weekday() + i)%7] day_img = self.textImage( weekday.upper(), small_font) weather = daily_weather[i] main = weather['main_weather'] - - + if main == 'Clouds': main = weather['description'] if main == 'Rain': main = weather['description'] - - + min_temp = self.convertTemp(weather['min_temp'], daily_weathers['temp']) max_temp = self.convertTemp(weather['max_temp'], daily_weathers['temp']) - - weather_img = Image.open(weather_dir + '/small_icons/' + weather_ids[main] + '.png') min_img = self.textImage( "{0:.0f}".format(min_temp), small_font, r=0, g=0, b=255) - - + max_img = self.textImage( "{0:.0f}".format(max_temp), small_font, r=255, g=0, b=0) img.paste(day_img, (x_offset +5, 9)) @@ -3741,7 +4624,7 @@ class StockTicker(): x_offset += 43 - img1 = img.crop((0,0,max(x_offset, crop_x) ,32)) + img1 = img.crop((0,0,max(x_offset, x_offset2 + 10) ,32)) imgs.append(img1) imgs.append(self.blank) # add the image text @@ -3966,7 +4849,13 @@ class StockTicker(): img = self.openImage(os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'user_uploads'), image)) img.thumbnail((99999, 32)) - + + if img.size[0] < 128: + diff = 128 - img.size[0] + new_image = Image.new('RGB',(128,32)) + new_image.paste(img,(64-int(img.size[0]/2),0)) + img = new_image + if all_settings['title'] and ind == 0: title_img = self.openImage('feature_titles/images.png') imgs.append(self.stitchImage([title_img, img])) @@ -4061,7 +4950,11 @@ class StockTicker(): for i, frame in enumerate(ImageSequence.Iterator(GIF)): frame = frame.convert('P') frame.thumbnail((128, 32),Image.NEAREST) - + if frame.size[0] < 128: + diff = 128 - frame.size[0] + new_image = Image.new('RGB',(128,32)) + new_image.paste(frame,(64-int(frame.size[0]/2),0)) + frame = new_image #f = self.stitchImage([title_img, frame]) frames.append(frame) @@ -4071,7 +4964,11 @@ class StockTicker(): frame = frame.convert('P') frame.thumbnail((128, 32),Image.NEAREST) - + if frame.size[0] < 128: + diff = 128 - frame.size[0] + new_image = Image.new('RGB',(128,32)) + new_image.paste(frame,(64-int(frame.size[0]/2),0)) + frame = new_image #frame = frame.resize((99999, 32)) #f = self.stitchImage([frame]) frames.append(frame) @@ -4309,7 +5206,249 @@ class StockTicker(): return self.stitchImage(image_list) + + def getIpoImage(self): + + f = open('csv/ipo_settings.json', 'r') + ipo_settings = json.load(f) + f.close() + if ipo_settings['title']: + title_img = self.openImage('feature_titles/ipo.png') + image_list = [title_img] + else: + image_list = [] + + font = ImageFont.load("./fonts/7x14B.pil") + font2 = ImageFont.load("./fonts/6x13.pil") + small_font = ImageFont.load("./fonts/6x10.pil") + + if ipo_settings['symbols'][0] != 'No Data': + try: + for ipo in ipo_settings['symbols']: + x_offset = 10 + x_offset2 = 10 + name_img = self.textImage(ipo['name'].upper(), font, r = 255, g = 255, b = 255) + + try: + if ipo['symbol'] == "": + symbol_img = self.textImage('($N/A)', font2, r = 255, g = 255, b = 255) + else: + symbol_img = self.textImage('($'+ ipo['symbol'] + ')', font2, r = 255, g = 255, b = 255) + except: + symbol_img = self.textImage('($N/A)', font2, r = 255, g = 255, b = 255) + + date_img = self.textImage(ipo['date'], font2, r = 255, g = 255, b = 0) + + status_1 = self.textImage('Status:', small_font, r=255, g=255, b=255) + if ipo['status'] == 'expected': + status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 255, g = 255, b = 0) # diff color + elif ipo['status'] == 'priced': + status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 0, g = 255, b = 0) # diff color + elif ipo['status'] == 'withdrawn': + status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 255, g = 0, b = 0) # diff color + elif ipo['status'] == 'filed': + status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 54, g = 69, b = 79) # diff color + + shares_1 = self.textImage('Shares:', small_font, r = 255, g = 255, b = 255) + try: + shares_img = self.textImage(ipo['shares'], small_font, r = 38, g = 59, b = 232) + except: + shares_img = self.textImage('N/A', small_font, r = 38, g = 59, b = 232) + + price_1 = self.textImage('Price:', small_font, r = 255, g = 255, b = 255) + try: + price_img = self.textImage(ipo['price'], small_font, r = 0, g = 255, b = 0) + except: + price_img = self.textImage('N/A', small_font, r = 0, g = 255, b = 0) + + sharesvalue_1 = self.textImage('Value:', small_font, r=255, g=255, b=255) + try: + sharesvalue_img = self.textImage(ipo['sharesvalue'], small_font, r = 213, g = 117, b = 0) + except: + sharesvalue_img = self.textImage('N/A', small_font, r = 213, g = 117, b = 0) + + img = Image.new('RGB', (max(x_offset + name_img.size[0] + 2 + symbol_img.size[0] + 8 + date_img.size[0], x_offset2 + status_1.size[0] + + status_img.size[0] + 8 + price_1.size[0] + price_img.size[0] + 8 + shares_1.size[0] + shares_img.size[0] +8 + + sharesvalue_1.size[0] + sharesvalue_img.size[0])+30,32)) + + img.paste(status_1,(x_offset2, 19)) + x_offset2 += status_1.size[0] + img.paste(status_img, (x_offset2, 19)) + x_offset2 += status_img.size[0] + 8 + img.paste(price_1, (x_offset2, 19)) + x_offset2 += price_1.size[0] + img.paste(price_img, (x_offset2, 19)) + x_offset2 += price_img.size[0] + 8 + img.paste(shares_1, (x_offset2, 19)) + x_offset2 += shares_1.size[0] + img.paste(shares_img, (x_offset2, 19)) + x_offset2 += shares_img.size[0] + 8 + img.paste(sharesvalue_1, (x_offset2, 19)) + x_offset2 += sharesvalue_1.size[0] + img.paste(sharesvalue_img, (x_offset2, 19)) + + img.paste(name_img, (x_offset,0)) + x_offset += name_img.size[0] + 2 + img.paste(symbol_img, (x_offset, 0)) + x_offset += symbol_img.size[0] + 8 + img.paste(date_img, (x_offset, 0)) + + line_image = Image.new("RGB", (name_img.size[0] + 2 + symbol_img.size[0] + 8 + date_img.size[0], 1)) + line_image1 = ImageDraw.Draw(line_image) + line_image1.line((0,0,name_img.size[0] + 2 + symbol_img.size[0] + 8 + date_img.size[0],0), fill="blue", width = 0) + img.paste(line_image, (10, max(name_img.size[1],symbol_img.size[1])-1)) + + image_list.append(img) + except: + time.sleep(0.1) + no_ipo = self.textImage('No Upcoming IPOs for the next 3 weeks.', font, r = 255, g = 255, b = 255) + img = Image.new('RGB', (no_ipo.size[0] + 15, 32)) + img.paste(no_ipo, (10, 10)) + image_list.append(img) + + elif ipo_settings['symbols'][0] == 'No Data': + time.sleep(0.1) + no_ipo = self.textImage('No Upcoming IPOs for the next 3 weeks.', font, r = 255, g = 255, b = 255) + img = Image.new('RGB', (no_ipo.size[0] + 15, 32)) + img.paste(no_ipo, (10, 10)) + image_list.append(img) + + return self.stitchImage(image_list) + + + def getIpoProfessional(self): + + f = open('csv/ipo_settings.json', 'r') + ipo_settings = json.load(f) + f.close() + + if ipo_settings['title']: + title_img = self.openImage('feature_titles/small_feature_titles/ipo.png') + image_list = [title_img] + else: + image_list = [] + + font = ImageFont.load("./fonts/5x8.pil") + small_font = ImageFont.load("./fonts/4x6.pil") + + if ipo_settings['symbols'][0] != 'No Data': + try: + for ipo in ipo_settings['symbols']: + x_offset = 10 + x_offset2 = 10 + name_img = self.textImage(ipo['name'].upper(), font, r = 255, g = 255, b = 255) + + try: + if ipo['symbol'] == "": + symbol_img = self.textImage('($N/A)', font, r = 255, g = 255, b = 255) + else: + symbol_img = self.textImage('($'+ ipo['symbol'] + ')', font, r = 255, g = 255, b = 255) + except: + symbol_img = self.textImage('($N/A)', font, r = 255, g = 255, b = 255) + + date_img = self.textImage(ipo['date'], font, r = 255, g = 255, b = 0) + + status_1 = self.textImage('Status:', small_font, r=255, g=255, b=255) + if ipo['status'] == 'expected': + status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 255, g = 255, b = 0) # diff color + elif ipo['status'] == 'priced': + status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 0, g = 255, b = 0) # diff color + elif ipo['status'] == 'withdrawn': + status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 255, g = 0, b = 0) # diff color + elif ipo['status'] == 'filed': + status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 54, g = 69, b = 79) # diff color + + shares_1 = self.textImage('Shares:', small_font, r = 255, g = 255, b = 255) + try: + shares_img = self.textImage(ipo['shares'], small_font, r = 38, g = 59, b = 232) + except: + shares_img = self.textImage('N/A', small_font, r = 38, g = 59, b = 232) + + price_1 = self.textImage('Price:', small_font, r = 255, g = 255, b = 255) + try: + price_img = self.textImage(ipo['price'], small_font, r = 0, g = 255, b = 0) + except: + price_img = self.textImage('N/A', small_font, r = 0, g = 255, b = 0) + + sharesvalue_1 = self.textImage('Value:', small_font, r=255, g=255, b=255) + try: + sharesvalue_img = self.textImage(ipo['sharesvalue'], small_font, r = 213, g = 117, b = 0) + except: + sharesvalue_img = self.textImage('N/A', small_font, r = 213, g = 117, b = 0) + + img = Image.new('RGB', (max(x_offset + name_img.size[0] + 2 + symbol_img.size[0] + 5 + date_img.size[0], x_offset2 + status_1.size[0] + + status_img.size[0] + 8 + price_1.size[0] + price_img.size[0] + 8 + shares_1.size[0] + shares_img.size[0] +8 + + sharesvalue_1.size[0] + sharesvalue_img.size[0])+30,16)) + + img.paste(status_1,(x_offset2, 10)) + x_offset2 += status_1.size[0] + img.paste(status_img, (x_offset2, 10)) + x_offset2 += status_img.size[0] + 8 + img.paste(price_1, (x_offset2, 10)) + x_offset2 += price_1.size[0] + img.paste(price_img, (x_offset2, 10)) + x_offset2 += price_img.size[0] + 8 + img.paste(shares_1, (x_offset2, 10)) + x_offset2 += shares_1.size[0] + img.paste(shares_img, (x_offset2, 10)) + x_offset2 += shares_img.size[0] + 8 + img.paste(sharesvalue_1, (x_offset2, 10)) + x_offset2 += sharesvalue_1.size[0] + img.paste(sharesvalue_img, (x_offset2, 10)) + + img.paste(name_img, (x_offset,0)) + x_offset += name_img.size[0] + 2 + img.paste(symbol_img, (x_offset, 0)) + x_offset += symbol_img.size[0] + 5 + img.paste(date_img, (x_offset, 0)) + + line_image = Image.new("RGB", (name_img.size[0] + 2 + symbol_img.size[0] + 5 + date_img.size[0], 1)) + line_image1 = ImageDraw.Draw(line_image) + line_image1.line((0,0,name_img.size[0] + 2 + symbol_img.size[0] + 5 + date_img.size[0],0), fill="blue", width = 0) + img.paste(line_image, (10, max(name_img.size[1],symbol_img.size[1])-2)) + + image_list.append(img) + except: + time.sleep(0.1) + font = ImageFont.load("./fonts/6x13.pil") + no_ipo = self.textImage('No Upcoming IPOs for the next 3 weeks.', font, r = 255, g = 255, b = 255) + img = Image.new('RGB', (no_ipo.size[0] + 15, 16)) + img.paste(no_ipo, (10, 1)) + image_list.append(img) + + elif ipo_settings['symbols'][0] == 'No Data': + time.sleep(0.1) + font = ImageFont.load("./fonts/6x13.pil") + no_ipo = self.textImage('No Upcoming IPOs for the next 3 weeks.', font, r = 255, g = 255, b = 255) + img = Image.new('RGB', (no_ipo.size[0] + 15, 16)) + img.paste(no_ipo, (10, 1)) + image_list.append(img) + + return self.stitchImage(image_list) + + + def ip_viewer(self): + + font = ImageFont.load("./fonts/6x10.pil") + + image = Image.new('RGB', (128, 32)) + + hostname = str(os.popen('hostname').read()).strip() + ".local:1024" + mac_add = str(os.popen('cat /sys/class/net/wlan0/address').read()).replace(" ", "").strip() + ip_add = str(os.popen('hostname -I').read()).replace(" ", "").strip() + ":1024" + + hostname_img = self.textImage(hostname, font, r = 255, g = 255 , b = 255) + ip_img = self.textImage(ip_add, font, r = 255, g = 255 , b = 255) + mac_img = self.textImage(mac_add, font, r = 255, g = 255 , b = 255) + + image.paste(hostname_img, (0,0)) + image.paste(ip_img, (0,12)) + image.paste(mac_img, (0,23)) + + stock_ticker.setImage(image) + time.sleep(10) + def displayStocks(self): @@ -4331,6 +5470,7 @@ class StockTicker(): movies = self.getMoviesProfessional() messages = self.getUserMessagesProfessional() images = self.getUserImagesProfessional() + ipo = self.getIpoProfessional() x_offset = 0 news.paste(weather, (x_offset, 16)) @@ -4361,6 +5501,8 @@ class StockTicker(): x_offset += messages.size[0] news.paste(images, (x_offset, 16)) x_offset += images.size[0] + news.paste(ipo, (x_offset, 16)) + x_offset += ipo.size[0] self.double_buffer = self.matrix.CreateFrameCanvas() while True: kill = stock_ticker.scrollImage(news, offset_x = 128) @@ -4441,6 +5583,9 @@ class StockTicker(): elif msg == 'MO': #movies self.scrollFunctionsAnimated(['movies', 'movies'],animation = 'traditional') + elif msg == 'IPO': #ipo + self.scrollFunctionsAnimated(['ipo', 'ipo'],animation = 'traditional') + elif msg == 'A': #everything #userSettings = ['display_gif', 'text', 'display_image', 'stocks', 'crypto', 'forex', 'today_weather', 'daily_weather', 'league_table', 'league_games', 'news'] # these wil be read from csv, just for demo @@ -4479,10 +5624,12 @@ class StockTicker(): self.displayGIF(start_GIF, delay = 0.02, repeat = False) #stock_ticker.setImage(start_image) + time.sleep(10) + self.resetMatrix() + time.sleep(2) + self.ip_viewer() time.sleep(2) self.resetMatrix() - - def run_intro_screen(self): dct = {"feature": "Custom Messages", "speed": "Medium", "animation": "Down", "title": False, "messages": [{"name": "welcome", "text": "Welcome to Fintic!", "text_colour": "White", "size": "Large", "background_colour": "Black"}, {"name": "get_started", "text": "To get started, connect your device to the \"Fintic Hotspot\" and access \"fintic.local:1024\" on your web browser. You can connect your ticker to Wi-Fi there.", "text_colour": "White", "size": "Small", "background_colour": "Black"}]} diff --git a/templates/index.html b/templates/index.html index 3237bb2..8809cee 100644 --- a/templates/index.html +++ b/templates/index.html @@ -67,7 +67,7 @@ - + @@ -102,9 +102,14 @@
-
- Hostname: {{ general_settings.hostname }}.local:1024
-
+ Hostname: {{ general_settings.hostname }}.local:1024
+ Scheduled Shutdown: {{ scheduler_settings.shutdown.hour }}:{{scheduler_settings.shutdown.minute}} {{scheduler_settings.timezone}}
+ Enabled:{{scheduler_settings.shutdown.enabled}}
+ Scheduled Reboot: {{ scheduler_settings.reboot.hour }}:{{scheduler_settings.reboot.minute}} {{scheduler_settings.timezone}}
+ Enabled:{{scheduler_settings.reboot.enabled}}
+ Scheduled Brightness: {% if scheduler_settings.brightness1.enabled or scheduler_settings.brightness2.enabled
+ or scheduler_settings.brightness3.enabled or scheduler_settings.brightness4.enabled %}Enabled
+ {% else %}Disabled{% endif %}
Version 1.3.3
+Version 1.3.4
@@ -399,23 +404,698 @@- Selected Format: - -
-