2
0
mirror of https://github.com/ComradCollective/Comrad synced 2024-11-05 21:20:51 +00:00
Comrad/komrade/app/main.py

471 lines
14 KiB
Python
Raw Normal View History

2020-08-12 08:02:51 +00:00
## CONFIG
# change this to your external ip address for your server
#(needs to be external to allow tor routing)
from config import *
2020-09-12 18:18:37 +00:00
import os,sys; sys.path.append(os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')),'..')))
from komrade import *
2020-09-14 10:50:57 +00:00
from komrade.api import Api
2020-09-01 22:41:06 +00:00
2020-08-19 13:01:37 +00:00
# monkeypatching the things that asyncio needs
import subprocess
subprocess.PIPE = -1 # noqa
subprocess.STDOUT = -2 # noqa
subprocess.DEVNULL = -3 # noqa
2020-08-18 17:25:15 +00:00
import asyncio
import os
2020-08-19 14:07:12 +00:00
os.environ['KIVY_EVENTLOOP'] = 'asyncio'
2020-08-18 17:25:15 +00:00
# loop = asyncio.get_event_loop()
# loop.set_debug(True)
2020-08-12 08:02:51 +00:00
# imports
2020-08-03 10:25:58 +00:00
from kivy.uix.screenmanager import Screen,ScreenManager
from kivymd.app import MDApp
2020-08-03 15:48:47 +00:00
from kivymd.uix.button import MDFillRoundFlatButton, MDIconButton
from kivymd.uix.toolbar import MDToolbar
from kivymd.uix.screen import MDScreen
2020-08-22 21:20:27 +00:00
from kivymd.uix.dialog import MDDialog
2020-08-03 10:25:58 +00:00
from kivy.lang import Builder
2020-08-03 15:48:47 +00:00
from kivy.uix.boxlayout import BoxLayout
from kivymd.theming import ThemeManager
from kivy.properties import ObjectProperty,ListProperty
import time,os
2020-08-03 15:48:47 +00:00
from collections import OrderedDict
from functools import partial
from kivy.uix.screenmanager import NoTransition
from kivymd.uix.label import MDLabel
from kivy.uix.widget import Widget
2020-08-03 16:29:03 +00:00
from kivymd.uix.list import OneLineListItem
from kivymd.uix.card import MDCard, MDSeparator
2020-08-06 10:24:09 +00:00
from kivymd.uix.boxlayout import MDBoxLayout
2020-08-03 20:16:30 +00:00
from kivy.uix.gridlayout import GridLayout
from kivy.metrics import dp
from kivy.properties import NumericProperty
2020-08-03 21:20:38 +00:00
from kivymd.uix.list import * #MDList, ILeftBody, IRightBody, ThreeLineAvatarListItem, TwoLineAvatarListItem, BaseListItem, ImageLeftWidget
from kivy.uix.image import Image, AsyncImage
2020-08-06 08:46:51 +00:00
import requests,json
2020-08-06 09:43:13 +00:00
from kivy.storage.jsonstore import JsonStore
from kivy.core.window import Window
2020-08-09 10:32:42 +00:00
from kivy.core.text import LabelBase
2020-08-17 20:59:53 +00:00
import shutil,sys
2020-08-13 17:41:31 +00:00
from kivy.uix.image import Image
2020-08-18 06:43:50 +00:00
import sys
sys.path.append("..") # Adds higher directory to python modules path.
2020-09-01 22:41:06 +00:00
from kivy.event import EventDispatcher
2020-08-19 13:01:37 +00:00
import threading,asyncio,sys
# raise Exception(str(Window.size))
2020-08-13 07:55:59 +00:00
Window.size = WINDOW_SIZE
# Window.fullscreen = True #'auto'
2020-08-09 10:32:42 +00:00
2020-08-17 16:23:40 +00:00
# with open('log.txt','w') as of:
# of.write('### LOG ###\n')
2020-08-19 23:26:25 +00:00
def rgb(r,g,b,a=1):
return (r/255,g/255,b/255,a)
2020-08-10 16:37:42 +00:00
2020-08-06 10:24:09 +00:00
class MyLayout(MDBoxLayout):
2020-08-03 15:48:47 +00:00
scr_mngr = ObjectProperty(None)
2020-08-10 20:38:00 +00:00
post_id = ObjectProperty()
2020-08-06 08:46:51 +00:00
2020-08-21 17:52:21 +00:00
@property
def app(self):
if not hasattr(self,'_app'):
from kivy.app import App
self._app = App.get_running_app()
return self._app
2020-08-19 23:26:25 +00:00
def rgb(self,r,g,b,a=1):
return rgb(r,g,b,a=a)
2020-08-03 15:48:47 +00:00
def change_screen(self, screen, *args):
self.scr_mngr.current = screen
2020-08-21 17:52:21 +00:00
def change_screen_from_uri(self,uri,*args):
2020-08-23 13:22:00 +00:00
self.app.uri=uri
2020-08-21 17:52:21 +00:00
screen_name = route(uri)
self.app.screen = screen_name
2020-08-21 21:15:20 +00:00
self.app.log(f'routing to {screen_name}')
self.scr_mngr.current = screen_name
2020-08-10 20:38:00 +00:00
def view_post(self,post_id):
self.post_id=post_id
self.change_screen('view')
2020-08-03 15:48:47 +00:00
2020-08-22 21:20:27 +00:00
class ProgressPopup(MDDialog): pass
class MessagePopup(MDDialog): pass
2020-08-06 10:24:09 +00:00
class MyBoxLayout(MDBoxLayout): pass
class MyLabel(MDLabel): pass
2020-08-03 20:16:30 +00:00
2020-08-19 23:26:25 +00:00
class MyToolbar(MDToolbar):
action_icon_color = ListProperty()
def update_action_bar(self, action_bar, action_bar_items):
action_bar.clear_widgets()
new_width = 0
for item in action_bar_items:
new_width += dp(48)
action_bar.add_widget(
MDIconButton(
icon=item[0],
on_release=item[1],
opposite_colors=True,
text_color=(self.specific_text_color if not self.action_icon_color else self.action_icon_color),
theme_text_color="Custom",
)
)
action_bar.width = new_width
def update_action_bar_text_colors(self, instance, value):
for child in self.ids["left_actions"].children:
if not self.action_icon_color:
child.text_color = self.specific_text_color
else:
child.text_color = self.action_icon_color
for child in self.ids["right_actions"].children:
if not self.action_icon_color:
child.text_color = self.specific_text_color
else:
child.text_color = self.action_icon_color
2020-08-09 10:32:42 +00:00
2020-08-03 16:29:03 +00:00
2020-08-06 08:46:51 +00:00
2020-08-09 10:32:42 +00:00
def get_tor_proxy_session():
session = requests.session()
# Tor uses the 9050 port as the default socks port
2020-08-13 19:41:19 +00:00
session.proxies = {'http': 'socks5://127.0.0.1:9150',
'https': 'socks5://127.0.0.1:9150'}
2020-08-09 10:32:42 +00:00
return session
def get_async_tor_proxy_session():
from requests_futures.sessions import FuturesSession
session = FuturesSession()
# Tor uses the 9050 port as the default socks port
2020-08-13 19:41:19 +00:00
session.proxies = {'http': 'socks5://127.0.0.1:9150',
'https': 'socks5://127.0.0.1:9150'}
return session
2020-08-09 10:32:42 +00:00
def get_tor_python_session():
from torpy.http.requests import TorRequests
with TorRequests() as tor_requests:
with tor_requests.get_session() as s:
return s
2020-08-13 17:41:31 +00:00
def draw_background(widget, img_fn='assets/bg.png'):
from kivy.core.image import Image as CoreImage
from kivy.graphics import Color, Rectangle
widget.canvas.before.clear()
with widget.canvas.before:
Color(.4, .4, .4, 1)
texture = CoreImage(img_fn).texture
texture.wrap = 'repeat'
nx = float(widget.width) / texture.width
ny = float(widget.height) / texture.height
Rectangle(pos=widget.pos, size=widget.size, texture=texture,
tex_coords=(0, 0, nx, 0, nx, ny, 0, ny))
2020-08-10 20:38:00 +00:00
#### LOOPER
2020-08-21 17:52:21 +00:00
def route(uri):
2020-08-21 21:15:20 +00:00
if not '/' in uri: return None
prefix=uri.split('/')[1] #,channel,rest = uri.split('/',3)
2020-08-21 17:52:21 +00:00
mapd = {
'inbox':'feed',
'outbox':'feed',
'login':'login',
}
return mapd.get(prefix,None)
2020-08-21 17:52:21 +00:00
# DEFAULT_SCREEN = route(DEFAULT_URI)
2020-08-03 10:25:58 +00:00
class MainApp(MDApp):
2020-08-06 10:24:09 +00:00
title = 'Komrade'
2020-08-06 09:43:13 +00:00
logged_in=False
2020-08-23 10:05:50 +00:00
# store = JsonStore('../p2p/.keys.json')
# store_global = JsonStore('../p2p/.keys.global.json')
store = JsonStore('app.json')
2020-08-06 09:43:13 +00:00
login_expiry = 60 * 60 * 24 * 7 # once a week
2020-08-13 17:41:31 +00:00
texture = ObjectProperty()
2020-08-22 21:20:27 +00:00
uri = '/inbox/world'
2020-08-13 17:41:31 +00:00
2020-08-17 13:33:26 +00:00
# def connect(self):
2020-08-16 14:59:36 +00:00
# # connect to kad?
2020-08-17 13:33:26 +00:00
# self.node = p2p.connect()
2020-08-19 23:26:25 +00:00
def rgb(self,*_): return rgb(*_)
2020-08-21 17:52:21 +00:00
def change_screen(self, screen, *args):
self.screen=screen
self.root.change_screen(screen,*args)
2020-08-23 13:22:00 +00:00
@property
def channel(self):
if not hasattr(self,'uri'): return None
if self.uri.count('/')<2: return None
return self.uri.split('/')[2]
2020-08-21 17:52:21 +00:00
def change_screen_from_uri(self,uri,*args):
self.uri=uri
2020-08-21 21:15:20 +00:00
self.log('CHANGING SCREEN',uri,'??')
2020-08-21 17:52:21 +00:00
return self.root.change_screen_from_uri(uri,*args)
2020-08-19 10:29:56 +00:00
@property
def logger(self):
if not hasattr(self,'_logger'):
import logging
handler = logging.StreamHandler()
2020-08-23 10:24:39 +00:00
formatter = logging.Formatter('[%(asctime)s]\n%(message)s\n')
2020-08-19 10:29:56 +00:00
handler.setFormatter(formatter)
2020-09-07 17:27:46 +00:00
self._logger = logger = logging.getLogger('komrade')
2020-08-19 10:29:56 +00:00
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return self._logger
2020-08-23 11:03:41 +00:00
def log(self,*args,**msgs):
2020-08-23 10:11:31 +00:00
line = ' '.join(str(x) for x in args)
2020-08-23 11:03:41 +00:00
self.logger.debug(line)
2020-08-16 14:59:36 +00:00
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.event_loop_worker = None
2020-08-18 17:25:15 +00:00
self.loop=asyncio.get_event_loop()
2020-08-19 10:29:56 +00:00
# load json storage
self.username=''
self.load_store()
2020-08-21 17:52:21 +00:00
self.uri=DEFAULT_URI
2020-09-01 22:41:06 +00:00
2020-08-19 10:29:56 +00:00
# connect to API
2020-09-02 09:57:07 +00:00
self.api = Api(log=self.log)
2020-08-19 10:29:56 +00:00
2020-08-21 17:52:21 +00:00
@property
2020-09-01 22:41:06 +00:00
async def node(self):
return await self.api.node
2020-08-09 10:32:42 +00:00
2020-08-12 06:49:14 +00:00
def get_username(self):
if hasattr(self,'username'): return self.username
self.load_store()
if hasattr(self,'username'): return self.username
return ''
2020-09-01 22:41:06 +00:00
2020-08-03 10:25:58 +00:00
def build(self):
2020-08-09 10:32:42 +00:00
# bind
2020-08-03 16:29:03 +00:00
global app,root
2020-08-03 15:48:47 +00:00
app = self
2020-08-17 16:23:40 +00:00
2020-08-19 10:29:56 +00:00
# load root
2020-08-10 21:16:36 +00:00
self.root = root = Builder.load_file('root.kv')
2020-08-13 17:41:31 +00:00
draw_background(self.root)
2020-08-06 12:55:26 +00:00
# edit logo
2020-08-19 23:26:25 +00:00
toolbar=root.ids.toolbar
toolbar.md_bg_color = root.rgb(*COLOR_TOOLBAR)
toolbar.action_icon_color=root.rgb(*COLOR_ICON)
logo=toolbar.ids.label_title
2020-08-06 12:55:26 +00:00
logo.font_name='assets/Strengthen.ttf'
logo.font_size='58dp'
logo.pos_hint={'center_y':0.43}
2020-08-19 23:26:25 +00:00
logo.text_color=root.rgb(*COLOR_LOGO)
2020-08-19 10:29:56 +00:00
2020-08-21 17:52:21 +00:00
self.root.change_screen_from_uri(self.uri if self.uri else DEFAULT_URI)
2020-08-19 10:29:56 +00:00
2020-08-03 16:29:03 +00:00
return self.root
2020-08-03 10:25:58 +00:00
2020-08-12 06:49:14 +00:00
def load_store(self):
if not self.store.exists('user'): return
userd=self.store.get('user')
2020-08-21 17:52:21 +00:00
if not userd: return
2020-08-06 08:46:51 +00:00
2020-08-21 17:52:21 +00:00
self.username = userd.get('username','')
2020-09-01 22:41:06 +00:00
2020-08-19 19:33:25 +00:00
async def upload(self,filename,file_id=None):
2020-08-19 10:29:56 +00:00
self.log('uploading filename:',filename)
2020-08-19 19:33:25 +00:00
rdata=await self.api.upload(filename,file_id=file_id)
2020-08-19 10:29:56 +00:00
self.log('upload result:',rdata)
2020-08-17 20:40:48 +00:00
if rdata is not None:
rdata['success']='File uploaded'
return rdata
return {'error':'Upload failed'}
2020-08-12 19:23:23 +00:00
2020-08-19 19:33:25 +00:00
async def download(self,file_id,output_fn=None):
2020-08-19 10:29:56 +00:00
self.log('downloading:',file_id)
2020-08-19 19:33:25 +00:00
file_dat = await self.api.download(file_id)
2020-08-20 11:48:26 +00:00
self.log('file_dat =',file_dat)
if not output_fn:
file_id=file_dat['id']
file_ext=file_dat['ext']
output_fn=os.path.join('cache',file_id[:3]+'/'+file_id[3:]+'.'+file_ext)
2020-08-12 19:23:23 +00:00
output_dir=os.path.dirname(output_fn)
if not os.path.exists(output_dir): os.makedirs(output_dir)
with open(output_fn,'wb') as of:
for data_piece in file_dat['parts_data']:
if data_piece is not None:
of.write(data_piece)
2020-08-12 19:23:23 +00:00
2020-08-22 20:11:19 +00:00
async def post(self, content='', file_id=None, file_ext=None, anonymous=False,channel='world'):
#timestamp=time.time()
jsond={}
#jsond['timestamp']=
if content: jsond['content']=str(content)
if file_id: jsond['file_id']=str(file_id)
if file_ext: jsond['file_ext']=str(file_ext)
2020-08-22 21:20:27 +00:00
if channel and channel[0]=='@': channel=channel[1:]
2020-08-23 09:59:52 +00:00
self.log(f'''app.post(
2020-08-22 06:12:50 +00:00
content={content},
file_id={file_id},
file_ext={file_ext},
anonymous={anonymous},
2020-08-22 20:11:19 +00:00
channel={channel},
2020-08-22 06:12:50 +00:00
[username={self.username}]'''
)
if not anonymous and self.username:
jsond['author']=self.username
2020-08-23 11:38:50 +00:00
#jsond['channel']=channel
2020-08-19 10:29:56 +00:00
self.log('posting:',jsond)
2020-08-23 11:38:50 +00:00
res=await self.api.post(jsond,channel = channel)
2020-08-17 20:40:48 +00:00
if 'success' in res:
self.root.change_screen('feed')
return {'post_id':res['post_id']}
2020-08-12 19:23:23 +00:00
2020-08-12 06:49:14 +00:00
2020-08-21 17:52:21 +00:00
@property
def keys(self):
return self.api.keys
2020-08-12 06:49:14 +00:00
2020-08-19 14:07:12 +00:00
async def get_post(self,post_id):
return await self.api.get_post(post_id)
2020-09-01 22:41:06 +00:00
async def get_posts(self,uri=b'/inbox/world'):
return await self.persona.read_inbox(uri)
# if uri.count('/')<2: raise Exception('not a URI: '+uri)
# if 'login' in uri:
# raise Exception('!!!! '+uri)
# self.log(f'app.get_posts(uri={uri} -> ...')
# data = await self.api.get_posts(uri)
# self.log(f'app.get_posts() got back from api.get_posts() a {type(data)}')
# newdata=[]
# for d in data:
# # self.log('data d:',d)
# if not 'val' in d: continue
# newdict = dict(d['val'].items())
# newdict['timestamp']=float(d['time'])
# newdict['to_name']=d['channel']
# newdata.append(newdict)
2020-08-21 07:27:27 +00:00
2020-09-01 22:41:06 +00:00
# # return index
# return newdata
2020-08-21 17:52:21 +00:00
async def get_channel_posts(self,channel,prefix='inbox'):
# am I allowed to?
if not channel in self.keys:
self.log('!! tsk tsk dont be nosy')
return
2020-08-22 14:45:48 +00:00
return await self.get_posts(uri='/'+os.path.join(prefix,channel))
2020-08-21 17:52:21 +00:00
async def get_channel_inbox(self,channel):
return await self.get_channel_posts(channel=channel,prefix='inbox')
async def get_channel_outbox(self,channel):
return await self.get_channel_posts(channel=channel,prefix='outbox')
2020-09-01 22:41:06 +00:00
async def get_my_posts(self):
return await self.persona.read_outbox()
2020-08-19 19:33:25 +00:00
2020-08-11 13:01:48 +00:00
2020-08-19 19:33:25 +00:00
### SYNCHRONOUS?
2020-08-19 14:07:12 +00:00
def app_func(self):
'''This will run both methods asynchronously and then block until they
are finished
'''
# self.other_task = asyncio.ensure_future(self.waste_time_freely())
self.other_task = asyncio.ensure_future(self.api.connect_forever())
async def run_wrapper():
# we don't actually need to set asyncio as the lib because it is
# the default, but it doesn't hurt to be explicit
await self.async_run() #async_lib='asyncio')
print('App done')
self.other_task.cancel()
return asyncio.gather(run_wrapper(), self.other_task)
2020-08-06 08:46:51 +00:00
2020-08-22 21:20:27 +00:00
def open_dialog(self,msg):
if not hasattr(self,'dialog') or not self.dialog:
self.dialog = ProgressPopup()
# raise Exception(self.dialog, msg)
self.dialog.text=msg
self.dialog.open()
#stop
def open_msg_dialog(self,msg):
from screens.post.post import MessagePopup,ProgressPopup
if not hasattr(self,'msg_dialog') or not self.msg_dialog:
self.msg_dialog = MessagePopup()
self.msg_dialog.ids.msg_label.text=msg
self.msg_dialog.open()
def close_dialog(self):
if hasattr(self,'dialog'):
self.dialog.dismiss()
def close_msg_dialog(self):
if hasattr(self,'msg_dialog'):
self.msg_dialog.dismiss()
2020-08-19 14:07:12 +00:00
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(MainApp().app_func())
loop.close()
2020-08-19 10:29:56 +00:00
2020-08-18 17:25:15 +00:00
2020-08-19 14:07:12 +00:00
# def main():
# # start_logger()
# App = MainApp()
# App.run()
# if __name__ == '__main__':
# # loop = asyncio.get_event_loop()
# # asyncio.set_event_loop(loop)
# # loop.run_until_complete(main())
# # loop.close()
# main()