Completed
Push — master ( 10a64c...d60bdd )
by Sepand
52s
created

is_sample_downloaded()   B

Complexity

Conditions 6

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
c 1
b 0
f 1
dl 0
loc 11
rs 8
1
import os
2
import shutil  # Library For Work With File In High Level Like Copy
3
import datetime  # For Adding System Time To Homepage
4
import webbrowser
5
from params import *
6
import socket
7
import requests
8
import re
9
import time
10
import sys
11
import urllib.request
12
meta_input=""
13
def is_sample_downloaded():
14
    download_list=[]
15
    if "profile.png"  not in os.listdir(image_dir):
16
        download_list.append(0)
17
    if "font.TTF" not in os.listdir(font_dir):
18
        download_list.append(1)
19
    if "resume.pdf"  not in os.listdir(doc_dir) and "resume.txt" not in os.listdir(doc_dir):
20
        download_list.extend([2,3])
21
    if "icon.ico" not in os.listdir(image_dir):
22
        download_list.append(4)
23
    return download_list
24
25
def download_lorem():
26
    if internet():
27
        urllib.request.urlretrieve("http://www.qpage.ir/sample/Latin-Lipsum.txt","Latin-Lipsum.txt")
28
    else:
29
        print("Error In Download Lorem")
30
def read_lorem(char=100):
31
    try:
32
        if "Latin-Lipsum.txt"  not in os.listdir():
33
            download_lorem()
34
        lorem_file=open("Latin-Lipsum.txt","r")
35
        lorem_text=lorem_file.read()
36
        lorem_file.close()
37
        return " ".join(lorem_text.split(" ")[:char])
38
    except:
39
        return None
40
def sample_site_download(item_list):
41
    try:
42
        if internet():
43
            for i in item_list:
44
                print("Downloading "+ sample_dict_message[i]+" . . . ["+str(i+1)+"/4]")
45
                print_line(70)
46
                urllib.request.urlretrieve(list(sample_dict_addr.values())[i],os.path.join(image_dir,list(sample_dict_addr.keys())[i]))
47
            print("Done! All Material Downloaded")
48
            print_line(70)
49
        else:
50
            print("Error In Internet Connection!")
51
            print_line(70)
52
    except:
53
        print("Error in downloading sample files check your internet conection")
54
        print_line(70)
55
def logger(status=False):
56
    file=open("build_log.txt","a")
57
    if status==False:
58
        file.write("Faild  "+str(datetime.datetime.now())+"\n")
59
    else:
60
        file.write("Sucess "+str(datetime.datetime.now())+"\n")
61
    file.close()
62
63
64
def print_line(number,char="-"):
65
    line=""
66
    for i in range(number):
67
        line=line+char
68
    print(line)
69
70
def name_standard(name):
71
    reponse_name=name[0].upper()+name[1:].lower()
72
    return reponse_name
73
def address_print():
74
    print_line(70,"*")
75
    print("Where--> "+work_dir)
76
    print_line(70, "*")
77
def create_folder():  # This Function Create Empty Folder At Begin
78
    folder_flag = 0
79
    list_of_folders = os.listdir(work_dir)
80
    for i in ["doc","image","output","font"]:
81
        if i not in list_of_folders:
82
            os.mkdir(i)
83
            folder_flag += 1
84
            if i=="doc":
85
                file = open(os.path.join(doc_dir, "index.txt"), "w")
86
                if read_lorem()==None:
87
                    file.write("This is For First Page . . .")
88
                else:
89
                    file.write(read_lorem())
90
                file.close()
91
    return bool(folder_flag)
92
93
94
def page_name_update():  # This Function Update Page Names
95
    for i in os.listdir(doc_dir):
96
        if i.find(".txt") != -1 and i[:-4].upper() != "INDEX":
97
            actual_name.append(i[:-4])
98
            page_name.append(i[:-4])
99
100
101
def menu_maker():  # Top Menu Maker In each html page
102
    result = "<center>"
103
    for i in range(len(page_name)):
104
        if page_name[i] == "Home":
105
            targets_blank = ""
106
        else:
107
            targets_blank = 'target="blank"'
108
        result = result + '\t<a href="' + actual_name[i] + '.html"' + targets_blank + '>' + name_standard(page_name[
109
            i]) + "</a>\n"  # Hyper Link To Each Page In HTML File
110
        result += "&nbsp\n"
111
    result += "</center>"
112
    result = result + "\t\t" + break_line  # Add Break line to End Of The Menu
113
    return result  # Return All Of The Menu
114
115
116
def menu_writer():  # Write menu_maker output in html file
117
    message = menu_maker()
118
    for i in range(len(page_name)):
119
        file = open(os.path.join(out_dir, actual_name[i] + ".html"), "a")
120
        file.write(message)
121
        file.close()
122
123
124
def print_meta():
125
    global meta_input
126
    meta_input = input("Please Enter Your Name : ")
127
    static_meta = '<meta name="description" content="Welcome to homepage of ' + meta_input + '"/>\n'
128
    static_meta=static_meta+'<meta property="og:title" content="'+meta_input+'"/>\n'
129
    static_meta=static_meta+'<meta property="og:site_name" content="'+meta_input+'"/>\n'
130
    static_meta=static_meta+'<meta property="og:image" content="favicon.ico" />\n'
131
    if len(meta_input) < 4:
132
        warnings.append("[Warning] Your input for name is too short!!")
133
    return static_meta
134
135
136
def html_init(name):  # Create Initial Form Of each Html Page Like Title And HTML  And Body Tag
137
    html_name = os.path.join(out_dir, name + ".html")
138
    file = open(html_name, "w")
139
    file.write("<html>\n")
140
    file.write("\t<head>\n")
141
    if name == "index":
142
        file.write("\t\t<title>Welcome To My Homepage</title>\n")
143
    else:
144
        file.write("\t\t<title>" + name_standard(name) + "</title>\n")
145
    file.write('<link rel="stylesheet" href="styles.css" type="text/css"/>\n')
146
    css_link = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
147
    file.write('<link rel="stylesheet" href= ' + css_link + ' type="text/style"/>\n')
148
149
    if name == 'index':  # Add meta only for index page
150
        file.write(print_meta())
151
152
    file.write("\t</head>\n")
153
    file.write('\t<body class="body_tag">\n')
154
    file.close()
155
156
157
def html_end(name):  # Create End Of The Html file
158
    html_name = os.path.join(out_dir, name + ".html")
159
    file = open(html_name, "a")
160
    file.write("\t</body>\n")
161
    file.write("</html>")
162
    file.close()
163
164
165
def close_files():
166
    for i in files:
167
        i.close()
168
169
def LSM_translate(line,center):
170
    line.strip()
171
    text = line
172
    header_start = '<h4 class="color_tag">'
173
    header_end = "</h4>"
174
    if line.find("[L]") != -1:
175
        header_start = '<h2 class="color_tag">'
176
        header_end = "</h2>"
177
        text = line[3:]
178
    elif line.find("[S]") != -1:
179
        header_start = '<h5 class="color_tag">'
180
        header_end = "</h5>"
181
        text = line[3:]
182
    elif line.find("[M]") != -1:
183
        text = line[3:]
184
    if center:  # Centerizes Text If Condition Is True For Manual Centering
185
        header_start = "<center>" + header_start
186
        header_end += "</center>"
187
    if text.find("[center]") != -1:  # Find Center Tag In Each Line
188
        header_start = "<center>" + header_start
189
        header_end += "</center>"
190
        text = text[:text.find("[center]")]
191
    return [text,header_end,header_start]
192
193
def print_text(text_file, file, center=False, close=False):  # Write Text Part Of Each Page
194
    text_code=""
195
    for line in text_file:
196
        if len(line)==1:
197
            text_code = space
198
        else:
199
            text_header=LSM_translate(line,center)
200
            text=text_header[0]
201
            header_end =text_header[1]
202
            header_start =text_header[2]
203
            text_code = header_start + text + header_end + "\n"
204
        file.write(text_code)
205
    if close:
206
        file.close()
207
208
209
def print_image(file, close=False, imformat="jpg"):  # Write Image Part OF The Page
210
    for i in range(len(size_box)):
211
        print(i, "-", size_box[i])
212
    image_size = int(input("Please Enter Profile Image Size : "))  # Choose Profile Image Size
213
    image_size_string = size_box[2]  # Getting Html String From size_box list default mode (Medium)
214
    if 0 <= image_size < len(size_box):
215
        image_size_string = size_box[image_size]
216
    image_code = '<center><img src="image.' + imformat + '"' + ', width=' + image_size_string + ' alt="profile image"></img></center>\n'
217
    file.write(image_code)
218
    if close:
219
        file.close()
220
221
222
def print_download(file, name, link, center=False, close=False):  # Create Download Link In Page
223
    link_code = "<a href=" + '"' + link + '"' + target_blank + '>' + name + "</a>"
224
    if center:
225
        link_code = "<center>" + link_code + "</center>"
226
    file.write(link_code + "\n")
227
    file.write(break_line)
228
    if close:
229
        file.close()
230
231
232
def print_adv(file, close=True):
233
    file.write(break_line)
234
    file.write(
235
        '<center><a href=' + '"' + homepage + '"' + target_blank + '>' + "Generated " + today_time + " By" + "QPage " + version + "</a> </center>")
236
    if close:
237
        file.close()
238
239
240
def contain(name):  # main function That Open Each Page HTML File and call other function to write data in it
241
    file = open(os.path.join(out_dir, name + ".html"), "a")
242
    text_file = open(os.path.join(doc_dir, name + ".txt"), "r")
243
    files.append(file)
244
    files.append(text_file)
245
    resume_name = ""
246
    image_name = ""
247
    imformat = "jpg"
248
    if name.upper() == "INDEX":
249
        file_of_images = os.listdir(image_dir)
250
        for i in range(len(file_of_images)):
251
            for form in imformat_box:
252
                if file_of_images[i].find("." + form) != -1:
253
                    image_name = os.path.join(image_dir, file_of_images[i])
254
                    imformat = form
255
                    global image_counter
256
                    image_counter=1
257
                    break
258
        shutil.copyfile(image_name, os.path.join(out_dir, "image." + imformat))
259
        print_image(file, imformat=imformat)
260
        print_text(text_file, file)
261
        print_adv(file)
262
    elif name.upper() == "RESUME":
263
        file_of_docs = os.listdir(doc_dir)
264
        for i in range(len(file_of_docs)):
265
            if file_of_docs[i].find(".pdf") != -1:
266
                resume_name = os.path.join(doc_dir, file_of_docs[i])
267
                global pdf_counter
268
                pdf_counter=1
269
                break
270
        shutil.copyfile(resume_name, os.path.join(out_dir, "Resume.pdf"))
271
        print_download(file, "Download Full Version", "Resume.pdf", center=True)
272
        print_text(text_file, file)
273
        # print_adv(file)
274
    else:
275
        print_text(text_file, file)
276
        # print_adv(file)
277
278
279
def clear_folder(path):  # This Function Get Path Of Foldr And Delte Its Contains
280
    if os.path.exists(path):
281
        list_of_files = os.listdir(path)
282
        for file in list_of_files:
283
            os.remove(os.path.join(path, file))
284
    else:
285
        os.mkdir(path)
286
287
288
def print_warning():
289
    print(str(len(warnings)) + " Warning , 0 Error")
290
    for i in range(len(warnings)):
291
        print(str(i + 1) + "-" + warnings[i])
292
293
294
def get_color_code():
295
    for i in range(len(color_box)):
296
        print(i, "-", color_box[i])
297
    back_color_code = int(input("Please enter your background color : "))
298
    if back_color_code not in range(7):
299
        back_color_code = 0
300
    text_color_code = int(input("Please enter your text color : "))
301
    if text_color_code not in range(7):
302
        text_color_code = 1
303
    return [back_color_code,text_color_code]
304
305
def color_code_map():
306
    [back_color_code, text_color_code]=get_color_code()
307
    if text_color_code == back_color_code:
308
        warnings.append("[Warning] Your text color and background color are same!!")
309
    background_color = color_box[back_color_code]  # convert code to color string in color_box
310
    text_color = color_box[text_color_code]  # convert code to color string in color_box
311
    return [background_color,text_color]
312
313
def css_font(font_folder):
314
    font_flag = 0  # 0 If there is no font file in font_folder
315
    current_font_format=None
316
    for i in font_folder:
317
        for j in range(len(font_format)):  # search for other font format in font box
318
            if i.lower().find(font_format[j]) != -1:  # If there is a font in font folder
319
                shutil.copyfile(os.path.join(font_dir, i),
320
                                os.path.join(out_dir, "qpage" + font_format[j]))  # copy font file to output folder
321
                font_flag = 1  # Turn Flag On
322
                current_font_format = font_format[j]  # font format of current selected font for css editing
323
    return [font_flag,current_font_format]
324
def css_creator():  # Ask For background and text color in
325
    font_section = 'font-family : Georgia , serif;\n'
326
    colors=color_code_map()
327
    background_color=colors[0]
328
    text_color=colors[1]
329
    font_folder = os.listdir(font_dir)
330
    details=css_font(font_folder)
331
    current_font_format=details[1]
332
    font_flag=details[0]
333
    css_file = open(os.path.join(out_dir, "styles.css"), "w")  # open css file
334
    if font_flag == 1:  # check flag if it is 1
335
        css_file.write(
336
            "@font-face{\nfont-family:qpagefont;\nsrc:url(qpage" + current_font_format + ");\n}\n")  # wrtie font-face in html
337
        font_section = "font-family:qpagefont;\n"  # Update Font Section For Body Tag
338
        for i in range(len(fontstyle_box)):
339
            print(i, "-", fontstyle_box[i])
340
        font_style = int(input(" Please choose your font style "))
341
        if font_style < len(fontstyle_box):
342
            font_style = fontstyle_box[font_style]
343
        else:
344
            font_style = "normal"
345
        font_section = font_section + "font-style:" + font_style + ";\n"
346
    else:
347
        warnings.append("[Warning] There is no specific font set for this website!!")
348
    css_file.write(
349
        ".body_tag{\n" + "background-color:" + background_color + ";\n" + font_section + css_margin +css_animation_1+ "}\n")  # write body tag
350
    css_file.write(".color_tag{\n" + "color:" + text_color + ";\n}")  # write color_tag in css
351
    css_file.write(css_animation_2)
352
    css_file.close()  # close css file
353
354
355
def preview():
356
    webbrowser.open(os.path.join(out_dir, "index.html"))
357
358
359
def error_finder():
360
    error_vector = []
361
    pass_vector = []
362
    pdf_counter = 0
363
    image_list = os.listdir(image_dir)
364
    doc_list = os.listdir(doc_dir)
365
    if image_counter == 1:
366
        pass_vector.append("[Pass] Your profile image in OK!!")
367
    else:
368
        error_vector.append("[Error] Your profile image is not in correct format")
369
    if len(doc_list) == 0:
370
        error_vector.append("[Error] There is no file in doc folder ( index.txt and .pdf file in necessary)")
371
    else:
372
        if "index.txt" in doc_list:
373
            pass_vector.append("[Pass] index.txt file OK!")
374
        else:
375
            error_vector.append("[Error] index.txt is not in doc folder!")
376
        if pdf_counter == 0:
377
            error_vector.append("[Error] Where Is Your Resume File? It should be in doc folder")
378
        else:
379
            pass_vector.append("[Pass] Your Resume File is OK!!")
380
    return [error_vector, pass_vector]
381
382
383
def icon_creator():
384
    icon_flag=0
385
    for file in os.listdir(image_dir):
386
        if file.endswith('ico'):
387
            shutil.copy(os.path.join(image_dir, file), out_dir)
388
            os.rename(os.path.join(out_dir, file), os.path.join(out_dir, 'favicon.ico'))
389
            icon_flag=1
390
            break
391
    if "favicon.ico" in os.listdir(work_dir) and icon_flag==0:
392
        shutil.copy(os.path.join(work_dir, "favicon.ico"), out_dir)
393
        warnings.append("[warning] There is no icon for this website")
394
def robot_maker(): # This Function Create Robots.txt for pages
395
    robots=open(os.path.join(out_dir,"robots.txt"),"w")
396
    robots.write("User-agent: *\n")
397
    robots.write("Disallow: ")
398
    robots.close()
399
def internet(host="8.8.8.8", port=53, timeout=3):
400
    try:
401
        socket.setdefaulttimeout(timeout)
402
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
403
        return True
404
    except Exception as ex:
405
        return False
406
def server():
407
    global meta_input
408
    url="http://sepkjaer.pythonanywhere.com/install"
409
    headers = {'content-type': 'application/json',"NAME":meta_input,"Version":"3"}
410
    response=requests.get(url,headers=headers)
411
    #print(response)
412
def version_control():
413
    try:
414
        print("Check for new version . . .")
415
        print_line(70)
416
        version_pattern=r"last_version:(.+)"
417
        if internet():
418
            response=requests.get("http://www.qpage.ir/releases.html")
419
            body=response.text
420
            last_version=float(re.findall(version_pattern,body)[0][:-3])
421
            if last_version>float(version):
422
                print_line(70)
423
                print("**New Version Of Qpage Is Available Now (Version "+str(last_version)+")**")
424
                print("Download Link -->"+"https://github.com/sepandhaghighi/qpage/archive/v"+str(last_version)+".zip")
425
                print_line(70)
426
            else:
427
                print ("Already Updated!!!")
428
                print_line(70)
429
    except:
430
        pass
431
def enter_to_exit(mode=False):
432
    print_line(70,"*")
433
    response=input("Enter [R] for restart Qpage and any other key to exit : ")
434
    if response.upper()!="R":
435
        sys.exit()
436
437
438
439
def wait_func(iteration):
440
    for i in range(iteration):
441
        time.sleep(1)
442
        print(".")
443
444
445
446