Пример #1
0
 def like_up(self, data):
     if data['article_ID'] in self.article_dict.keys():
         json_path = f"../learn/jsons/{data['article_ID']}.json"
         self.lock.acquire()
         article = jd.json2dict(json_path)
         self.lock.release()
         if article == {}:
             return
         article["like_list"].append(data["self_ID"])
         article["latest_edit_time"] = data["latest_edit_time"]
         self.lock.acquire()
     elif data['article_ID'] in self.comment_dict.keys():
         json_path = f"../learn/jsons/{self.comment_dict.get(data['article_ID'])}.json"
         self.lock.acquire()
         article = jd.json2dict(json_path)
         self.lock.release()
         if article == {}:
             return
         article["like_list"].append(data["self_ID"])
         article["latest_edit_time"] = data["latest_edit_time"]
         self.lock.acquire()
     else:
         return
     jd.dict2json(json_path, article)
     self.lock.release()
Пример #2
0
    def __init__(self, loop):
        self.lock = threading.Lock()
        self.loop = loop
        lists = jd.json2dict('../learn/jsons/source.json')

        if lists == {}:
            self.friend_list = []
            self.friend_request_list = []
            self.article_dict = {}
            self.waiting_response_list = []
            self.ip_address_dict = {}
            self.my_article_list = []
            self.user_data_dict = {}
            self.comment_dict = {}
            self.update_source()
        else:
            self.friend_list = lists['friend_list']
            self.friend_request_list = lists['friend_request_list']
            self.article_dict = lists['article_dict']
            self.waiting_response_list = lists['waiting_response_list']
            self.ip_address_dict = lists['ip_address_dict']
            self.my_article_list = lists['my_article_list']
            self.user_data_dict = lists['user_data_dict']
            self.comment_dict = lists['comment_dict']
        self.my_data = jd.json2dict('../learn/jsons/my_data.json')
        self.new_article_list = []
        self.new_comment_dict = {}
        if self.my_data != {}:
            self.check_file_exists()
            if self.user_data_dict == {}:
                self.user_data_dict[self.my_data['ID']] = \
                    {
                        "user_name": self.my_data['user_name'],
                        "profile_picture": self.my_data['profile_picture']
                    }
Пример #3
0
def my_articles(request):
    if asyncio_server.handler.my_data == {}:
        return first_login(request)
    article_list = asyncio_server.handler.my_article_list
    my_data = asyncio_server.handler.my_data
    articles = []
    for article_id in article_list:
        article = jd.json2dict(f'../learn/jsons/{article_id}.json')

        user_data = asyncio_server.handler.user_data_dict.get(
            article['owner_ID'])
        # if article_owner not in dict
        if user_data is None:
            # check if owner is self
            if article['owner_ID'] == my_data['ID']:
                article["user_name"] = my_data['user_name']
                article["img"] = my_data['profile_picture']
            else:
                continue
        else:
            article["user_name"] = user_data['user_name']
            article["img"] = my_data['profile_picture']
        print(article)
        articles.append(article)

    return render(
        request, "home.html", {
            "articles": articles,
            "my_id": my_data["ID"],
            "my_picture": my_data['profile_picture'],
            'my_name': my_data['user_name']
        })
Пример #4
0
 def add_friend_request(self, data, peername):
     print('add_friend')
     if data['selfs_ID'] in self.friend_list:
         return
     picture = data["profile_picture"]
     file_type = picture["file_type"]
     binary = picture["binary"]
     file_name = self.save_picture(file_type, binary, 'profile_picture')
     json_path = f"../learn/jsons/{data['selfs_ID']}.json"
     print(json_path)
     self.lock.acquire()
     js = jd.json2dict(json_path)
     self.lock.release()
     print(js)
     if js != {}:
         try:
             os.remove(f"../learn/images/{js['profile_picture']}")
         except FileNotFoundError:
             pass
     data["profile_picture"] = file_name
     self.lock.acquire()
     jd.dict2json(json_path, data)
     self.lock.release()
     if data['selfs_ID'] not in self.friend_request_list:
         self.ip_address_dict[data['selfs_ID']] = peername[0]
         self.friend_request_list.append(data['selfs_ID'])
         self.update_source()
Пример #5
0
def like_list(request, article_id):
    article_id = str(article_id)
    article = jd.json2dict(f"../learn/jsons/{article_id}.json")
    user_list = []
    for user_id in article['like_list']:
        user_data = asyncio_server.handler.user_data_dict.get(user_id)
        if user_data is not None:
            user_list.append(user_data['user_name'])
    print(user_list)
    return render(request, "like_list.html", {"user_list": user_list})
Пример #6
0
def comments(comment_list):
    return_value = []
    handler = asyncio_server.handler

    for comment_id in comment_list:
        comment = jd.json2dict(f'../learn/jsons/{comment_id}.json')
        user_data = handler.user_data_dict.get(comment['owner_ID'])
        comment_html = f'<li><div class="comment"><table><tbody><tr><td><img src="/buddybook/media/{user_data["profile_picture"]}"></td><td colspan="4">{user_data["user_name"]}</td><td></td></tr><tr><td colspan="6" class="contents">{comment["content"]}</td></tr><tr><td colspan="3" class="like {comment["article_ID"]}" onclick="like("{comment["article_ID"]}")">like</td><td colspan="3" class="make_comment" onclick="comment("{comment["article_ID"]}")">Comment</td></tr></tbody></table></div></li>'
        comment_html += f'<li><ul class="{comment["article_ID"]}" style="display: none;"><li><div class="add_comment"><table><tbody><tr><td colspan="6"><input type="text" class="{comment["article_ID"]}"></td><td class="send_comment" onclick="send_comment("{comment["article_ID"]}")">Send</td></tr></tbody></table></div></li></li></ul>'
        return_value.append(comment_html)
    return mark_safe("".join(return_value))
Пример #7
0
def open_browser():
    def check_django_status():
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
            return client.connect_ex(('127.0.0.1', 8000)) == 0

    data = jd.json2dict('./learn/jsons/my_data.json')
    handler = webbrowser.get()
    while not check_django_status():
        pass
    if data == {}:
        handler.open('http://127.0.0.1:8000/buddybook/first_login')
    else:
        handler.open("http://127.0.0.1:8000/buddybook/")
Пример #8
0
def update_articles(request):
    if asyncio_server.handler.my_data == {}:
        return first_login(request)
    handler = asyncio_server.handler
    if len(handler.new_article_list):

        article_id = handler.new_article_list.pop(0)

        root_article_id = handler.new_comment_dict.get(article_id)
        handler.new_comment_dict.pop(article_id)
        if root_article_id is None:
            article = jd.json2dict(f"../learn/jsons/{article_id}.json")
        else:
            article = jd.json2dict(f"../learn/jsons/{root_article_id}.json")
        owner_data = handler.user_data_dict.get(article['owner_ID'])
        if owner_data is not None:
            article['user_name'] = owner_data['user_name']
            article['img'] = owner_data['profile_picture']
        else:
            return update_articles(request)
        return render(request, "article.html", {"article": article})
    else:
        return HttpResponse(" ", status=200)
Пример #9
0
    def post_article(self, data):
        articles = []
        for article in data["article_list"]:
            # if no parent -> root article
            if article["parent_ID"] == "":
                if article['owner_ID'] in self.friend_list:
                    articles.append(article)
            else:
                if article["root_article_ID"] in self.article_dict.keys():
                    self.lock.acquire()
                    jd.dict2json(
                        f"../learn/jsons/{article['article_ID']}.json",
                        article)
                    self.lock.release()
                    old_data = jd.json2dict(
                        f"../learn/jsons/{article['root_article_ID']}.json")
                    if article['article_ID'] not in old_data['comment_list']:
                        old_data['comment_list'].append(article['article_ID'])
                    old_data['latest_edit_time'] = article['latest_edit_time']
                    jd.dict2json(
                        f'../learn/jsons/{article["root_article_ID"]}.json',
                        old_data)
                    self.article_dict[article["root_article_ID"]] = article[
                        'latest_edit_time']
                    self.new_comment_dict[
                        article["article_ID"]] = article["root_article_ID"]
                    self.new_article_list.append(article["article_ID"])
                    self.update_source()
                    return

        for article in articles:
            # if article is on local -> compare edit time
            if self.article_dict.get(article['article_ID']) is not None:
                if self.article_dict[
                        article['article_ID']] > article['latest_edit_time']:
                    continue
            image_list = []
            for image in article["image_content"]:
                image_list.append(
                    self.save_picture(image['file_type'], image['binary']))
            article['image_content'] = image_list
            article['comment_list'] = []
            jd.dict2json(f'../learn/jsons/{article["article_ID"]}.json',
                         article)
            # set local article edit time to received article edit time
            self.article_dict[
                article['article_ID']] = article['latest_edit_time']
            self.new_article_list.append(article['article_ID'])
        self.update_source()
Пример #10
0
 def update_personal_data(self, data):
     #loop through list
     for personal_data in data['personal_data_list']:
         #read old_data
         self.lock.acquire()
         old_data = jd.json2dict(
             f'../learn/jsons/{personal_data["ID"]}.json')
         self.lock.release()
         if old_data != {}:
             #skip if old_data is newer than current one
             if old_data.get("latest_edit_time") is not None:
                 if old_data['latest_edit_time'] > personal_data[
                         'latest_edit_time']:
                     continue
                 try:
                     #remove old pictures
                     os.remove("../learn/images/" +
                               old_data["profile_picture"])
                     os.remove("../learn/images/" +
                               old_data["background_picture"])
                 except FileNotFoundError:
                     pass
             else:
                 try:
                     #remove old pictures
                     os.remove("../learn/images/" +
                               old_data["profile_picture"])
                 except FileNotFoundError:
                     pass
         #save pictures and put file_name to json
         picture = personal_data["profile_picture"]
         file_name = self.save_picture(picture['file_type'],
                                       picture['binary'], 'profile_picture')
         personal_data["profile_picture"] = file_name
         picture = personal_data["background_picture"]
         file_name = self.save_picture(picture['file_type'],
                                       picture['binary'],
                                       'background_picture')
         personal_data["background_picture"] = file_name
         json_path = f'../learn/jsons/{personal_data["ID"]}.json'
         #update json file
         self.lock.acquire()
         jd.dict2json(json_path, personal_data)
         self.lock.release()
         self.user_data_dict[personal_data["ID"]] = {
             "user_name": personal_data["user_name"],
             "profile_picture": personal_data["profile_picture"]
         }
         self.update_source()
Пример #11
0
def send_like_up(request, article_id):
    article_id = str(article_id)
    self_id = asyncio_server.handler.my_data["ID"]
    old_data = jd.json2dict(f"../learn/jsons/{article_id}.json")
    old_data['like_list'].append(self_id)
    jd.dict2json(f"../learn/jsons/{article_id}.json", old_data)
    my_request = \
        {
            "header": "like_up",
            "body":
                {
                    "self_ID": self_id,
                    "article_ID": article_id,
                    "latest_edit_time": timestamp()
                }
        }
    asyncio_server.handler.send_like_up(my_request)
    return HttpResponse(status=200)
Пример #12
0
def reply(request):
    if asyncio_server.handler.my_data == {}:
        return first_login(request)
    request_list = []
    for ID in asyncio_server.handler.friend_request_list:
        asyncio_server.handler.lock.acquire()
        my_request = jd.json2dict(f'../learn/jsons/{ID}.json')
        asyncio_server.handler.lock.release()
        if not os.path.exists(
                f'../learn/images/{my_request["profile_picture"]}'):
            my_request[
                'profile_picture'] = f'{my_request["profile_picture"][:36]}.gif'
            shutil.copy('../learn/static/profile_picture_not_found.gif',
                        f'../learn/images/{my_request["profile_picture"]}')
            asyncio_server.handler.lock.acquire()
            jd.dict2json(f'../learn/jsons/{ID}.json', my_request)
            asyncio_server.handler.lock.release()
        request_list.append(my_request)

    return render(request, 'friend_requests.html',
                  {"request_list": request_list})
Пример #13
0
def send_add_friend(request):
    if request.META['REQUEST_METHOD'] == 'GET':
        return HttpResponse(status=404)
    if request.method == 'POST':
        target = request.POST['ip_address']

        asyncio_server.handler.lock.acquire()
        my_data_dict = jd.json2dict('../learn/jsons/my_data.json')
        asyncio_server.handler.lock.release()

        asyncio_server.handler.check_file_exists()
        with open(f'../learn/images/{my_data_dict["profile_picture"]}',
                  'rb') as fp:
            binary = fp.read()
            binary = str(base64.b64encode(binary), "utf-8")

        my_request = \
            {
                "header": 'add_friend_request',
                "body":
                    {
                        'selfs_ID': my_data_dict['ID'],
                        'user_name': my_data_dict['user_name'],
                        'profile_context': my_data_dict['profile_context'],
                        'profile_picture':
                            {
                                'file_type': my_data_dict['profile_picture'].split('.')[-1],
                                'binary': binary
                            }
                    }
            }
        print(
            requestHandle.verify_data(my_request['body'],
                                      my_request['header']))
        asyncio_server.handler.send_add_friend_request(my_request, target)
    else:
        return HttpResponse()
    return HttpResponse(status=200)
Пример #14
0
def send_new_article(request):
    if not request.is_ajax():
        return HttpResponse(status=404)
    handler = asyncio_server.handler
    print(request.POST)
    image_content = []
    image_list = []
    for f in request.FILES.getlist('image'):
        file_type = f.name.split('.')[-1]
        file_name = f"{str(uuid.uuid4())}.{file_type}"
        image_list.append(file_name)
        binary = []
        with open(f'../learn/images/{file_name}', 'wb') as fp:
            for chunk in f.chunks():
                fp.write(chunk)
                binary.append(chunk)
        image_content.append({
            "file_type":
            file_type,
            "binary":
            str(base64.b64encode(b"".join(binary)), 'utf-8')
        })

    article_id = str(uuid.uuid4())
    try:
        my_article = \
            {
                "latest_edit_time": timestamp(),
                "article_ID": article_id,
                "owner_ID": asyncio_server.handler.my_data['ID'],
                "parent_ID": request.POST['parent_ID'],
                "root_article_ID": request.POST['root_article_ID'],
                "content": request.POST['content'],
                "image_content": image_content,
                "like_list": [],
                "position_tag": [i for i in request.POST.getlist('position_tag') if i != ""],
                "friend_tag": [i for i in request.POST.getlist('friend_tag') if i != ""],
                "comment_list": [],
                "deletion": False
            }
        my_request = \
            {
                "header": "post_article",
                "body": { "article_list": [my_article] }
            }
        handler.send_post_article(my_request)
        my_article["image_content"] = image_list
        handler.lock.acquire()
        jd.dict2json(f'../learn/jsons/{article_id}.json', my_article)
        handler.lock.release()
        if my_article['root_article_ID'] == "":
            root_article_id = article_id
            handler.my_article_list.append(article_id)
        else:
            root_article_id = my_article['root_article_ID']
            handler.lock.acquire()
            old_article = jd.json2dict(
                f'../learn/jsons/{root_article_id}.json')
            handler.lock.release()
            old_article['comment_list'].append(article_id)
            old_article['latest_edit_time'] = my_article['latest_edit_time']
            handler.lock.acquire()
            jd.dict2json(f'../learn/jsons/{root_article_id}.json', old_article)
            handler.lock.release()

        handler.article_dict[root_article_id] = my_article['latest_edit_time']
        handler.update_source()
        handler.send_post_article(my_request)
    except Exception as e:
        print(e)
        return HttpResponse(status=500)
    if my_article['root_article_ID'] != '':
        return HttpResponse(str(uuid.uuid4()), status=200)
    my_article["user_name"] = handler.my_data['user_name']
    my_article["img"] = handler.my_data['profile_picture']
    return render(request, "article.html", {"article": my_article})