def act_subtitles(self, data): """ Returns subtitles to a movie in a given language :param data: An array containing the id of the movie and the requested language for the subtitles :returns: The subtitles file """ # data is [imdb[id], language] imdb, language = split_string(data) path = Stream.Files_dict[imdb][0] + "Subtitles\\" + language + ".srt" # Some languages have difference encodings try: with open(path) as f: subtitles = f.read() print("Normal encoding") except UnicodeDecodeError: try: with open(path, encoding="utf8") as f: subtitles = f.read() print("UTF-8 encoding") except UnicodeDecodeError: try: with open(path, encoding="utf16") as f: subtitles = f.read() print("UTF-16 encoding") except UnicodeDecodeError: with open(path, encoding="latin-1") as f: subtitles = f.read() print("Latin-1 encoding") return subtitles
def act_get_title(self, data): """ Returns the requested title :param data: [type, imdb, user] :returns: Title with the given data / An error message """ print("Attempting to get title with data:", data) data = split_string(data) record = self.database.get_title(data[:-1]) if record == "Error": return "Error" record, link = record record += self.database.get_user_rating(data) bookmarks = self.database.access_bookmarks(["get", data[2], data[1]]) record.append(bookmarks) lists = self.database.get_user_attr( ["lists", data[2], data[1], "true"]) record.append(lists) can_stream = data[1].split("/")[-1] if data[0] == "Movie": can_stream = str(can_stream in Stream.Files_dict) else: can_stream = str(can_stream in Stream.shows_dict) record.append(("can_stream", can_stream)) separators = find_sep(str(record), maximum=2) new = [] for i in range(len(record)): new.append(separators[1].join(record[i])) title = separators[0].join(new) title = "({0})({1}){0}".format(*separators[:2]) + title print("Database's answer:", title) return title
def act_confirm_register(self, data): """ Confirms the registration of a user :param data: An array containing the email address of the user and the confirmation PIN code of the user :returns: The database's answer: Success / Failure message """ print("Attempting to confirm register with data: ", data) answer = self.database.activate_user(split_string(data)) print("Database's answer:", answer) return answer
def act_bookmarks(self, data): """ Does a certain action on the bookmarks of a user :param data: An array containing the email of the user and more data which depends on the wished action to be done on the bookmarks. (See database_access.py for all states) :returns: Depends on the wished action that the user wants to do on the bookmarks (See database_access.py for all states) """ print("Attempting to get bookmarks with data: ", data) answer = self.database.access_bookmarks(split_string(data)) print("Database's answer:", answer) return answer
def act_request(self, data): """ Requests an attribute of a given user :param data: An array containing the request of the client, the email address of the user and other variable (depending of the request of the client) (See get_user_attr in database_access.py) :returns: The database's answer: Requested data / Failure message """ print("Attempting request with data:", data) answer = self.database.get_user_attr(split_string(data)) print("Database's answer:", answer) return answer
def act_edit_lists(self, data): """ Does a certain action on the lists of a user :param data: An array containing the email of the user and more data which depends on the wished action to do on the lists (See database_access.py for all states) :returns: Depends on the wished action that the user wants to do on the lists (See database_access.py for all states) """ print("Attempting to edit lists with data: ", data) answer = self.database.set_user_list(split_string(data)) print("Database's answer:", answer) print(answer) return answer
def act_rate_title(self, data): """ Rates a title :param data: An array containing the user who is rating the title, the imdb link of the title, the type of the title and the new rating of the user to the title :returns: Updated rating with a suitable message / An error message """ print("Attempting to rate title with data:", data) answer = self.database.set_user_rating(split_string(data)) if not isinstance(answer, str): answer = join_arr(*answer) print("Database's answer: ", answer) return answer
def act_search(self, data): """ Attempts to search title with given data :param data: [Search term] :returns: The title it found or an error message if it couldn't find any title """ print("Attempting search with data:", data) records = self.database.search_title(split_string(data)) if records == "Error": return "Error" # [[Movies...], [Shows...]] answer = records print("Database's answer:", answer) return answer
def act_edit_user(self, data): """ Edits the user's data State A: :param data: ["name", email, update name, password] State B: :param data: ["password", email, update password, old password] State C: :param data: ["language", email, updated language preference] :returns: A success message or an error message """ print("Attempting to edit user with data", data) data = split_string(data) answer = self.database.edit_user(data) print("Database answer: " + answer) return answer
def act_register(self, data): """ Registers a user to the database :param data: User (An array containing the email of the user, the password of the user, the birth date of the user and the name of the user) :returns: The database's answer: Success / Failure message """ print("Attempting register with data:", data) data = split_string(data) answer, pin = self.database.register(data) if answer == "SUCCESS": pin_answer = self.send_pin(data[1], pin) if pin_answer.startswith("Error"): answer = pin_answer self.database.delete_user(data[0]) print("Database's answer:", answer) return str(answer)
def run(self, client_socket): """ Runs the server for a single client :param client_socket: The socket of the client """ self.lock.acquire() num = self.thread_counter self.thread_counter += 1 self.lock.release() print("Starting thread:", num) condition = True try: msg = choice(whitespace) msg = "({}){}".format(msg, msg.join(ARRAY_SEPARATORS)) self.send_client_response(client_socket, msg) while condition: request = self.receive_client_request(client_socket) data, sep = split_string(request, True) if not sep: condition = False continue action, data = data[0].upper(), data[1] print("Action: {}\t\tData: {}".format(action, data)) try: print("Attempting action") response = Server.actions[action](self, data) print("Succeed doing action") except RuntimeError: # KeyError: response = "Non-existing" condition = False except UnicodeEncodeError: response = "Unicode chars made the code suicide" print("Response:", response) if isinstance(response, list): sep = find_sep(str(response), maximum=1)[0] msg = sep.join(response) self.send_client_response(client_socket, msg) else: self.send_client_response(client_socket, response) except socket.error as e: print("Exception: {}\n\t\t{}".format(str(type(e)), e)) print("Ending thread:", num)
def act_login(self, data): """ :param data: string that contains both email and password that the user tried to login with :return: Success case: returns "Success" and username of the user Failure case: reason for failed login """ print("Attempting to login with data:", data) answer = self.database.check_user_login(*split_string(data)) print("Database's answer:", answer) if isinstance(answer, tuple): answer = list(answer) answer[1] = join_arr(*eval(answer[1])) answer[2] = eval(answer[2]) if len(answer[2]): answer[2] = join_arr(*answer[2]) else: answer = answer[:2] answer = "Success:" + join_arr(*answer) return answer
def act_add_title(self, data): """ Tries to add a given title to the database Returns a suitable message for success or failure :param data: [name, date, type, user] :returns: The database's answer: Added title / Failure message """ print("Attempting to add title with data:", data) if not is_english(data): return "Search only works in english." data = split_string(data) title = self.database.search_title_data(data[:-1]) if not isinstance(title, TitleClass): return title answer = self.database.add_title(title) if isinstance(answer, str): return answer request = join_arr(*answer, data[-1]) answer = self.act_get_title(request) print("Database's answer:", answer) return answer
def act_stream(self, data): """ :param data: An array containing: Full imdb link of a title and the user's email :returns: Streaming address of the title """ print("Attempting to stream with data: ", data) data = split_string(data) imdb = data[0].split("/")[-1] if imdb in Stream.Files_dict: url = ":8080/Watch/" + imdb languages = Stream.Files_dict[imdb][1] data = ["languages", data[1]] user_preferences = self.database.get_user_attr(data) for language in user_preferences: if language in languages: subtitles = self.act_subtitles(join_arr(imdb, language)) return join_arr(url, join_arr(*languages), subtitles) return join_arr(url, join_arr(*languages)) return "Error: Video not found"
def edit_user(self, data): """ :param data: :returns: """ data = Database.injection_arr(data) if len(data) == 3 and data[0] == "languages": data[2] = repr(split_string(data[2])) print("DATA: ", data) self.cursor.execute("""UPDATE Users SET languages=\"{}\" WHERE email=\"{}\"""".format(*data[:0:-1])) self.connection.commit() elif len(data) == 4: user = list( self.cursor.execute("""SELECT name, password FROM Users WHERE email=\"{}\"""".format(data[1])))[0] if user[1] != data[-1]: return "Bad password" if data[0] == "name": if data[2] == user[0]: return "You can't change your username to your current one" elif data[0] == "password": if data[2] == user[1]: return "You can't change your password to your current one" else: return "An error has occurred" query = """UPDATE Users SET {0}=\"{2}\" WHERE email=\"{1}\"""".format(*data[:-1]) print(query) self.cursor.execute(query) self.connection.commit() else: return "Non existing request" return "SUCCESS"
def set_user_list(self, data): """ Changes value for something inside of the user's lists The change depends on the array parameter 'data' State A: Gets [User email, lists to add a title to, lists to remove a title from, title imdb list] Adds the given title to given lists and removes the given title From given lists :param data: [User mail, add_to_lists, delete_from_lists, imdb_link] :returns: Either an error message or updated user lists with items count (See get_user_attr - State E) State B: Gets [User email, the word "create" and a string that represents a list's name] Tries to add the list to the user's lists :param data: [User mail, "create", list_name] :returns: Either an error message or updated user lists with items count (See get_user_attr - State E) State C: Gets (User email, the word "delete" and an array of strings Each string is the name of a user's list) :param data: [User mail, "delete", lists] :returns: Either an error message or updated user lists with items count (See get_user_attr - State E) """ data = Database.injection_arr(data) print("Sets user list with data: ", data) if len(data) < 3: return "Error: Developers still cant code" lists = list( self.cursor.execute("""SELECT lists FROM Users WHERE email = \"{}\"""".format(data[0]))) lists = eval(lists[0][0]) for list_name in lists: lists[list_name] = set(lists[list_name]) # State B / State C if data[1] in ("create", "delete"): if len(data) > 3: return "Error: Failed randomly, as usual" # State B if data[1] == "create": if data[2] in lists: return "Error: Could not create an existing list" lists[data[2]] = [] # State C elif data[1] == "delete": names = split_string(data[2]) for name in names: if name not in lists: return "Error: Could not remove a non-existing entry" lists.pop(name) print("Success?\tCREATE_DELETE") # State A elif len(data) == 4: data[1] = split_string(data[1]) data[2] = split_string(data[2]) imdb = data[-1] for list_name in data[1]: print("NAME: ", list_name) if list_name: lists[list_name].add(imdb) for list_name in data[2]: print("NAME: ", list_name) if list_name: try: lists[list_name].remove(imdb) except KeyError: print("Error or something", lists, list_name) else: return "Error: Non-existing request" for list_name in lists: lists[list_name] = list(lists[list_name]) self.cursor.execute("""UPDATE Users SET lists = {} WHERE email = \"{}\"""".format(repr(str(lists)), data[0])) self.connection.commit() return self.get_user_attr(["lists", data[0], "Useless", "false"])