Completed
Push — master ( f2d4d4...bde681 )
by Sepand
48s
created

sample_site_download()   A

Complexity

Conditions 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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