Ejemplo n.º 1
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()
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
def set_personal_data(request):
    if request.META['REQUEST_METHOD'] == 'POST':
        handler = asyncio_server.handler
        if handler.my_data != {}:
            try:
                os.remove("../learn/images/" +
                          handler.my_data["profile_picture"])
                os.remove("../learn/images/" +
                          handler.my_data["background_picture"])
            except FileNotFoundError:
                pass
            my_id = handler.my_data["ID"]
        else:
            my_id = str(uuid.uuid4())
        position = -1
        my_request = {
            'user_name': request.POST['user_name'],
            'profile_context': request.POST['profile_context'],
            "ID": my_id,
            'latest_edit_time': timestamp()
        }
        print(my_request)
        my_data = my_request.copy()
        for key in request.FILES.keys():
            while request.FILES[key].name[position] != '.':
                position -= 1

            picture = {"file_type": request.FILES[key].name[position + 1:]}
            file_name = f"{str(uuid.uuid4())}.{picture['file_type']}"
            binary = []
            with open('../learn/images/' + file_name, 'wb') as fp:
                for chunk in request.FILES[key].chunks():
                    fp.write(chunk)
                    binary.append(chunk)
            picture["binary"] = str(base64.b64encode(b"".join(binary)),
                                    'utf-8')
            my_data[key] = file_name
            my_request[key] = picture
        handler.lock.acquire()
        jd.dict2json('../learn/jsons/my_data.json', my_data)
        handler.lock.release()
        my_request = \
            {
                "header": "update_personal_data",
                "body": { "personal_data_list": [my_request] }
            }
        handler.send_update_personal_data(my_request)
        handler.my_data = my_data
        handler.user_data_dict[my_id] = \
            {
                "user_name": my_data['user_name'],
                "profile_picture": my_data['profile_picture']
            }
        return HttpResponse(status=200)
    return HttpResponse(status=404)
Ejemplo n.º 4
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()
Ejemplo n.º 5
0
 def update_source(self):
     js = \
         {
             "friend_list": self.friend_list,
             "friend_request_list": self.friend_request_list,
             "article_dict": self.article_dict,
             "waiting_response_list": self.waiting_response_list,
             "ip_address_dict": self.ip_address_dict,
             "my_article_list": self.my_article_list,
             "comment_dict": self.comment_dict,
             "user_data_dict": self.user_data_dict
         }
     self.lock.acquire()
     jd.dict2json('../learn/jsons/source.json', js)
     self.lock.release()
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
 def check_file_exists(self):
     if not os.path.exists(
             f'../learn/images/{self.my_data["background_picture"]}'):
         file_name = f'{self.my_data["background_picture"][:36]}.png'
         print('Background not found')
         print('Copying not found image...')
         shutil.copy('../learn/static/background_not_found.png',
                     f'../learn/images/{file_name}')
         self.my_data["background_picture"] = file_name
         jd.dict2json('../learn/jsons/my_data.json', self.my_data)
     if not os.path.exists(
             f'../learn/images/{self.my_data["profile_picture"]}'):
         file_name = f'{self.my_data["profile_picture"][:36]}.gif'
         print('Profile picture not found')
         print('Copying not found image...')
         shutil.copy('../learn/static/profile_picture_not_found.gif',
                     f'../learn/images/{file_name}')
         self.my_data["profile_picture"] = file_name
         jd.dict2json('../learn/jsons/my_data.json', self.my_data)
Ejemplo n.º 8
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})
Ejemplo n.º 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()
Ejemplo n.º 10
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})