CCMain.m 254 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCAutoUpload.h"
  35. #import "NCBridgeSwift.h"
  36. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate>
  37. {
  38. tableMetadata *_metadata;
  39. BOOL _isRoot;
  40. BOOL _isViewDidLoad;
  41. BOOL _isOfflineServerUrl;
  42. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  43. BOOL _isSelectedMode;
  44. NSMutableArray *_selectedMetadatas;
  45. NSMutableArray *_queueSelector;
  46. NSUInteger _numSelectedMetadatas;
  47. UIImageView *_ImageTitleHomeCryptoCloud;
  48. UIView *_reMenuBackgroundView;
  49. UITapGestureRecognizer *_singleFingerTap;
  50. NSString *_directoryGroupBy;
  51. NSString *_directoryOrder;
  52. NSUInteger _failedAttempts;
  53. NSDate *_lockUntilDate;
  54. NSString *_fatherPermission;
  55. UIRefreshControl *_refreshControl;
  56. UIDocumentInteractionController *_docController;
  57. CCHud *_hud;
  58. CCHud *_hudDeterminate;
  59. // Datasource
  60. CCSectionDataSourceMetadata *_sectionDataSource;
  61. NSDate *_dateReadDataSource;
  62. // Search
  63. BOOL _isSearchMode;
  64. NSString *_searchFileName;
  65. NSMutableArray *_searchResultMetadatas;
  66. NSString *_depth;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. }
  74. @end
  75. @implementation CCMain
  76. #pragma --------------------------------------------------------------------------------------------
  77. #pragma mark ===== Init =====
  78. #pragma --------------------------------------------------------------------------------------------
  79. - (id)initWithCoder:(NSCoder *)aDecoder
  80. {
  81. if (self = [super initWithCoder:aDecoder]) {
  82. _directoryOrder = [CCUtility getOrderSettings];
  83. _directoryGroupBy = [CCUtility getGroupBySettings];
  84. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  89. }
  90. return self;
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark ===== View =====
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (void)viewDidLoad
  96. {
  97. [super viewDidLoad];
  98. // init object
  99. _metadata = [tableMetadata new];
  100. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  101. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _selectedMetadatas = [NSMutableArray new];
  103. _queueSelector = [NSMutableArray new];
  104. _sectionDataSource = [CCSectionDataSourceMetadata new];
  105. _isViewDidLoad = YES;
  106. _fatherPermission = @"";
  107. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  108. _searchResultMetadatas = [NSMutableArray new];
  109. _searchFileName = @"";
  110. _depth = @"0";
  111. _noFilesSearchTitle = @"";
  112. _noFilesSearchDescription = @"";
  113. // delegate
  114. self.tableView.delegate = self;
  115. self.tableView.tableFooterView = [UIView new];
  116. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  117. self.tableView.emptyDataSetDelegate = self;
  118. self.tableView.emptyDataSetSource = self;
  119. self.searchController.delegate = self;
  120. self.searchController.searchBar.delegate = self;
  121. [[CCNetworking sharedNetworking] settingDelegate:self];
  122. // Custom Cell
  123. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  125. // long press recognizer TableView
  126. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  127. [self.tableView addGestureRecognizer:longPressRecognizer];
  128. // Pull-to-Refresh
  129. [self createRefreshControl];
  130. // Register for 3D Touch Previewing if available
  131. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  132. {
  133. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  134. }
  135. // Back Button
  136. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  137. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  138. // reMenu Background
  139. _reMenuBackgroundView = [[UIView alloc] init];
  140. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  141. // if this is not Main (the Main uses inizializeMain)
  142. if (_isRoot == NO && app.activeAccount.length > 0) {
  143. // Settings this folder & delegate & Loading datasource
  144. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  145. // Load Datasource
  146. [self reloadDatasource:_serverUrl selector:nil];
  147. // Read (File) Folder
  148. [self readFileReloadFolder];
  149. }
  150. // Title
  151. [self setTitle];
  152. // Search
  153. self.definesPresentationContext = YES;
  154. self.searchController.searchResultsUpdater = self;
  155. self.searchController.dimsBackgroundDuringPresentation = NO;
  156. self.tableView.tableHeaderView = self.searchController.searchBar;
  157. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  158. [self.searchController.searchBar sizeToFit];
  159. self.searchController.searchBar.delegate = self;
  160. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  161. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  162. if (_isRoot)
  163. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  164. else
  165. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  166. } else {
  167. self.searchController.searchBar.scopeButtonTitles = nil;
  168. }
  169. // Hide Search Filed on Load
  170. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  171. }
  172. // Apparirà
  173. - (void)viewWillAppear:(BOOL)animated
  174. {
  175. [super viewWillAppear:animated];
  176. // test
  177. if (app.activeAccount.length == 0)
  178. return;
  179. // Settings this folder & delegate & Loading datasource
  180. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  181. [[CCNetworking sharedNetworking] settingDelegate:self];
  182. // Color
  183. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  184. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  185. if (_isSelectedMode)
  186. [self setUINavigationBarSelected];
  187. else
  188. [self setUINavigationBarDefault];
  189. // Plus Button
  190. [app plusButtonVisibile:true];
  191. }
  192. // E' arrivato
  193. - (void)viewDidAppear:(BOOL)animated
  194. {
  195. [super viewDidAppear:animated];
  196. // Active Main
  197. app.activeMain = self;
  198. // Test viewDidLoad
  199. if (_isViewDidLoad) {
  200. _isViewDidLoad = NO;
  201. } else {
  202. if (app.activeAccount.length > 0) {
  203. // Load Datasource
  204. [self reloadDatasource:_serverUrl selector:nil];
  205. // Read (file) Folder
  206. [self readFileReloadFolder];
  207. }
  208. }
  209. // Title
  210. [self setTitle];
  211. }
  212. - (void)viewWillDisappear:(BOOL)animated
  213. {
  214. [super viewWillDisappear:animated];
  215. [self closeAllMenu];
  216. }
  217. - (void)didReceiveMemoryWarning
  218. {
  219. [super didReceiveMemoryWarning];
  220. // Dispose of any resources that can be recreated.
  221. }
  222. - (BOOL)prefersStatusBarHidden
  223. {
  224. return NO;
  225. }
  226. // detect scroll for remove keyboard in search mode
  227. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  228. {
  229. if (_isSearchMode && scrollView == self.tableView) {
  230. [self.searchController.searchBar endEditing:YES];
  231. }
  232. }
  233. - (void)changeTheming
  234. {
  235. if (self.isViewLoaded && self.view.window)
  236. [app changeTheming:self];
  237. // Refresh control
  238. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  239. // Reload Table View
  240. [self tableViewReload];
  241. }
  242. #pragma --------------------------------------------------------------------------------------------
  243. #pragma mark ===== Initizlize Mail =====
  244. #pragma --------------------------------------------------------------------------------------------
  245. - (void)initializeMain:(NSNotification *)notification
  246. {
  247. _directoryGroupBy = nil;
  248. _directoryOrder = nil;
  249. _dateReadDataSource = nil;
  250. // test
  251. if (app.activeAccount.length == 0)
  252. return;
  253. if ([app.listMainVC count] == 0 || _isRoot) {
  254. // This is Root
  255. _isRoot = YES;
  256. // Crypto Mode
  257. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  258. app.isCryptoCloudMode = NO;
  259. } else {
  260. app.isCryptoCloudMode = YES;
  261. }
  262. // go Home
  263. [self.navigationController popToRootViewControllerAnimated:NO];
  264. // Remove search mode
  265. [self cancelSearchBar];
  266. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  267. _isFolderEncrypted = NO;
  268. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  269. // add list
  270. [app.listMainVC setObject:self forKey:_serverUrl];
  271. // setting Networking
  272. [[CCNetworking sharedNetworking] settingDelegate:self];
  273. [[CCNetworking sharedNetworking] settingAccount];
  274. // populate shared Link & User variable
  275. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  276. if (results) {
  277. app.sharesLink = results[0];
  278. app.sharesUserAndGroup = results[1];
  279. }
  280. // Setting Theming
  281. [app settingThemingColorBrand];
  282. // Load Datasource
  283. [self reloadDatasource:_serverUrl selector:nil];
  284. // Read (File) Folder
  285. [self readFileReloadFolder];
  286. // Load photo datasorce
  287. if (app.activePhotos)
  288. [app.activePhotos reloadDatasourceForced];
  289. // remove all of detail
  290. if (app.activeDetail)
  291. [app.activeDetail removeAllView];
  292. // remove all Notification Messages
  293. [app.listOfNotifications removeAllObjects];
  294. // home main
  295. app.homeMain = self;
  296. // Initializations
  297. [app applicationInitialized];
  298. } else {
  299. // reload datasource
  300. [self reloadDatasource:_serverUrl selector:nil];
  301. }
  302. }
  303. #pragma --------------------------------------------------------------------------------------------
  304. #pragma mark ==== DZNEmptyDataSetSource ====
  305. #pragma --------------------------------------------------------------------------------------------
  306. /*
  307. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  308. {
  309. if(_isSearchMode)
  310. return NO;
  311. else
  312. return YES;
  313. }
  314. */
  315. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  316. {
  317. return YES;
  318. }
  319. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. return [UIColor whiteColor];
  322. }
  323. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  324. {
  325. if (_isSearchMode)
  326. return [UIImage imageNamed:@"searchBig"];
  327. else
  328. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  329. }
  330. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  331. {
  332. NSString *text;
  333. if (_isSearchMode)
  334. text = _noFilesSearchTitle;
  335. else
  336. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  337. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  338. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  339. }
  340. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  341. {
  342. NSString *text;
  343. if (_isSearchMode)
  344. text = _noFilesSearchDescription;
  345. else
  346. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  347. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  348. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  349. paragraph.alignment = NSTextAlignmentCenter;
  350. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  351. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  352. }
  353. #pragma --------------------------------------------------------------------------------------------
  354. #pragma mark ===== Text Field =====
  355. #pragma --------------------------------------------------------------------------------------------
  356. - (void)minCharTextFieldDidChange:(UITextField *)sender
  357. {
  358. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  359. if (alertController)
  360. {
  361. UITextField *fileName = alertController.textFields.firstObject;
  362. UIAlertAction *okAction = alertController.actions.lastObject;
  363. okAction.enabled = fileName.text.length > 0;
  364. }
  365. }
  366. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  367. [textField selectAll:textField];
  368. }
  369. #pragma --------------------------------------------------------------------------------------------
  370. #pragma mark ===== Graphic Window =====
  371. #pragma --------------------------------------------------------------------------------------------
  372. - (void)createRefreshControl
  373. {
  374. _refreshControl = [UIRefreshControl new];
  375. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  376. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  377. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  378. [self setRefreshControl:_refreshControl];
  379. }
  380. - (void)deleteRefreshControl
  381. {
  382. [_refreshControl endRefreshing];
  383. self.refreshControl = nil;
  384. }
  385. - (void)refreshControlTarget
  386. {
  387. [self readFolderWithForced:YES serverUrl:_serverUrl];
  388. // Actuate `Peek` feedback (weak boom)
  389. AudioServicesPlaySystemSound(1519);
  390. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  391. }
  392. - (void)setTitle
  393. {
  394. // Color text self.navigationItem.title
  395. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  396. if (_isSelectedMode) {
  397. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  398. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  399. self.navigationItem.titleView = nil;
  400. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  401. } else {
  402. // we are in home : LOGO BRAND
  403. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  404. self.navigationItem.title = nil;
  405. if ([app.reachability isReachable] == NO)
  406. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  407. else
  408. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  409. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  410. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  411. [singleTap setNumberOfTapsRequired:1];
  412. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  413. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  414. } else {
  415. self.navigationItem.title = _titleMain;
  416. }
  417. }
  418. }
  419. - (void)setUINavigationBarDefault
  420. {
  421. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  422. UIBarButtonItem *buttonMore, *buttonNotification;
  423. // =
  424. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  425. buttonMore.enabled = true;
  426. // <
  427. self.navigationController.navigationBar.hidden = NO;
  428. // Notification
  429. if ([app.listOfNotifications count] > 0) {
  430. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  431. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  432. buttonNotification.enabled = true;
  433. }
  434. if (buttonNotification)
  435. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  436. else
  437. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  438. self.navigationItem.leftBarButtonItem = nil;
  439. }
  440. - (void)setUINavigationBarSelected
  441. {
  442. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  443. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  444. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  445. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  446. self.navigationItem.leftBarButtonItem = leftButton;
  447. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  448. }
  449. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  450. {
  451. [self closeAllMenu];
  452. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  453. }];
  454. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  455. }
  456. - (void)cancelSelect
  457. {
  458. [self tableViewSelect:NO];
  459. [app.reSelectMenu close];
  460. }
  461. - (void)closeAllMenu
  462. {
  463. // close Menu
  464. [app.reSelectMenu close];
  465. [app.reMainMenu close];
  466. // Close Menu Logo
  467. [CCMenuAccount dismissMenu];
  468. }
  469. #pragma --------------------------------------------------------------------------------------------
  470. #pragma mark ===== Document Picker =====
  471. #pragma --------------------------------------------------------------------------------------------
  472. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  473. {
  474. NSLog(@"Cancelled");
  475. }
  476. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  477. {
  478. NSLog(@"Cancelled");
  479. }
  480. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  481. {
  482. documentPicker.delegate = self;
  483. [self presentViewController:documentPicker animated:YES completion:nil];
  484. }
  485. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  486. {
  487. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  488. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  489. __block NSError *error;
  490. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  491. NSString *fileName = [url lastPathComponent];
  492. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  493. NSData *data = [NSData dataWithContentsOfURL:newURL];
  494. if (data && error == nil) {
  495. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  496. // Upload File
  497. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  498. } else {
  499. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  500. }
  501. } else {
  502. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  503. }
  504. }];
  505. }
  506. }
  507. - (void)openImportDocumentPicker
  508. {
  509. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  510. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  511. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  512. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  513. documentProviderMenu.delegate = self;
  514. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  515. }
  516. #pragma --------------------------------------------------------------------------------------------
  517. #pragma mark ===== Assets Picker =====
  518. #pragma --------------------------------------------------------------------------------------------
  519. - (void)openAssetsPickerController
  520. {
  521. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  522. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  523. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  524. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  525. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  526. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  527. dispatch_async(dispatch_get_main_queue(), ^{
  528. // init picker
  529. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  530. // set delegate
  531. picker.delegate = self;
  532. // to show selection order
  533. //picker.showsSelectionIndex = YES;
  534. // to present picker as a form sheet in iPad
  535. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  536. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  537. // present picker
  538. [self presentViewController:picker animated:YES completion:nil];
  539. });
  540. }];
  541. }
  542. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  543. {
  544. [picker dismissViewControllerAnimated:YES completion:^{
  545. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  546. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  547. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  548. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  549. [self presentViewController:navigationController animated:YES completion:nil];
  550. }];
  551. }
  552. #pragma --------------------------------------------------------------------------------------------
  553. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  554. #pragma --------------------------------------------------------------------------------------------
  555. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  556. {
  557. // evitiamo il rimando della eventuale photo e/o video
  558. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  559. if (tableAccount.autoUpload) {
  560. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  561. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  562. }
  563. }
  564. /*
  565. #pragma --------------------------------------------------------------------------------------------
  566. #pragma mark ===== UnZipFile =====
  567. #pragma --------------------------------------------------------------------------------------------
  568. - (void)unZipFile:(NSString *)fileID
  569. {
  570. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  571. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  572. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  573. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  574. dispatch_async(dispatch_get_main_queue(), ^{
  575. float progress = (float) entryNumber / (float)total;
  576. [_hudDeterminate progress:progress];
  577. });
  578. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  579. dispatch_async(dispatch_get_main_queue(), ^{
  580. [_hudDeterminate hideHud];
  581. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  582. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  583. });
  584. }];
  585. });
  586. }
  587. */
  588. #pragma --------------------------------------------------------------------------------------------
  589. #pragma mark ===== Create New (OpenModel) =====
  590. #pragma --------------------------------------------------------------------------------------------
  591. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  592. {
  593. UIViewController *viewController;
  594. NSString *fileName, *uuid, *fileID, *serverUrl;
  595. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  596. [self.tableView deselectRowAtIndexPath:index animated:NO];
  597. if (isnew) {
  598. fileName = nil;
  599. uuid = [CCUtility getUUID];
  600. fileID = nil;
  601. serverUrl = _serverUrl;
  602. } else {
  603. fileName = _metadata.fileName;
  604. uuid = _metadata.uuid;
  605. fileID = _metadata.fileID;
  606. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  607. }
  608. if ([tipo isEqualToString:@"cartadicredito"])
  609. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  610. if ([tipo isEqualToString:@"bancomat"])
  611. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  612. if ([tipo isEqualToString:@"contocorrente"])
  613. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  614. if ([tipo isEqualToString:@"accountweb"])
  615. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  616. if ([tipo isEqualToString:@"patenteguida"])
  617. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  618. if ([tipo isEqualToString:@"cartaidentita"])
  619. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  620. if ([tipo isEqualToString:@"passaporto"])
  621. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  622. if ([tipo isEqualToString:@"note"]) {
  623. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  624. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  625. [self presentViewController:navigationController animated:YES completion:nil];
  626. } else {
  627. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  628. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  629. [self presentViewController:navigationController animated:YES completion:nil];
  630. }
  631. }
  632. // New folder or new photo or video
  633. - (void)returnCreate:(NSInteger)type
  634. {
  635. switch (type) {
  636. /* PLAIN */
  637. case k_returnCreateFolderPlain: {
  638. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  639. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  640. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  641. }];
  642. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  643. NSLog(@"Cancel action");
  644. }];
  645. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  646. UITextField *fileName = alertController.textFields.firstObject;
  647. [self createFolder:fileName.text autoUploadDirectory:NO];
  648. }];
  649. okAction.enabled = NO;
  650. [alertController addAction:cancelAction];
  651. [alertController addAction:okAction];
  652. [self presentViewController:alertController animated:YES completion:nil];
  653. }
  654. break;
  655. case k_returnCreateFotoVideoPlain: {
  656. _isPickerCriptate = false;
  657. [self openAssetsPickerController];
  658. }
  659. break;
  660. case k_returnCreateFilePlain: {
  661. _isPickerCriptate = false;
  662. [self openImportDocumentPicker];
  663. }
  664. break;
  665. /* ENCRYPTED */
  666. case k_returnCreateFolderEncrypted: {
  667. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  668. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  669. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  670. }];
  671. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  672. NSLog(@"Cancel action");
  673. }];
  674. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  675. UITextField *fileName = alertController.textFields.firstObject;
  676. [self createFolderEncrypted:fileName.text];
  677. }];
  678. okAction.enabled = NO;
  679. [alertController addAction:cancelAction];
  680. [alertController addAction:okAction];
  681. [self presentViewController:alertController animated:YES completion:nil];
  682. }
  683. break;
  684. case k_returnCreateFotoVideoEncrypted: {
  685. _isPickerCriptate = true;
  686. [self openAssetsPickerController];
  687. }
  688. break;
  689. case k_returnCreateFileEncrypted: {
  690. _isPickerCriptate = true;
  691. [self openImportDocumentPicker];
  692. }
  693. break;
  694. /* UTILITY */
  695. case k_returnNote:
  696. [self openModel:@"note" isNew:true];
  697. break;
  698. case k_returnAccountWeb:
  699. [self openModel:@"accountweb" isNew:true];
  700. break;
  701. /* BANK */
  702. case k_returnCartaDiCredito:
  703. [self openModel:@"cartadicredito" isNew:true];
  704. break;
  705. case k_returnBancomat:
  706. [self openModel:@"bancomat" isNew:true];
  707. break;
  708. case k_returnContoCorrente:
  709. [self openModel:@"contocorrente" isNew:true];
  710. break;
  711. /* DOCUMENT */
  712. case k_returnPatenteGuida:
  713. [self openModel:@"patenteguida" isNew:true];
  714. break;
  715. case k_returnCartaIdentita:
  716. [self openModel:@"cartaidentita" isNew:true];
  717. break;
  718. case k_returnPassaporto:
  719. [self openModel:@"passaporto" isNew:true];
  720. break;
  721. }
  722. }
  723. #pragma --------------------------------------------------------------------------------------------
  724. #pragma mark ===== Save selected File =====
  725. #pragma --------------------------------------------------------------------------------------------
  726. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  727. {
  728. if (error)
  729. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  730. else
  731. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  732. }
  733. - (void)saveSelectedFiles
  734. {
  735. NSLog(@"[LOG] Start download selected files ...");
  736. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  737. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  738. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  739. for (tableMetadata *metadata in metadatas) {
  740. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  741. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  742. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  743. }
  744. }
  745. [_hud hideHud];
  746. });
  747. [self tableViewSelect:NO];
  748. }
  749. #pragma --------------------------------------------------------------------------------------------
  750. #pragma mark ===== Change Password =====
  751. #pragma --------------------------------------------------------------------------------------------
  752. - (void) loginSuccess:(NSInteger)loginType
  753. {
  754. [self readFolderWithForced:YES serverUrl:_serverUrl];
  755. }
  756. - (void)changePasswordAccount
  757. {
  758. // Brand
  759. if ([NCBrandOptions sharedInstance].use_login_web) {
  760. _loginWeb = [CCLoginWeb new];
  761. _loginWeb.delegate = self;
  762. _loginWeb.loginType = loginModifyPasswordUser;
  763. dispatch_async(dispatch_get_main_queue(), ^ {
  764. [_loginWeb presentModalWithDefaultTheme:self];
  765. });
  766. } else {
  767. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  768. _loginVC.delegate = self;
  769. _loginVC.loginType = loginModifyPasswordUser;
  770. [self presentViewController:_loginVC animated:YES completion:nil];
  771. }
  772. }
  773. #pragma mark -
  774. #pragma --------------------------------------------------------------------------------------------
  775. #pragma mark ===== Peek & Pop =====
  776. #pragma --------------------------------------------------------------------------------------------
  777. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  778. {
  779. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  780. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  781. if (metadata.thumbnailExists && !metadata.cryptated) {
  782. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  783. if (cell) {
  784. previewingContext.sourceRect = cell.frame;
  785. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  786. vc.delegate = self;
  787. vc.metadata = metadata;
  788. return vc;
  789. }
  790. }
  791. return nil;
  792. }
  793. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  794. {
  795. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  796. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  797. }
  798. #pragma mark -
  799. #pragma --------------------------------------------------------------------------------------------
  800. #pragma mark ==== External Sites ====
  801. #pragma --------------------------------------------------------------------------------------------
  802. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  803. {
  804. [[NCManageDatabase sharedInstance] deleteExternalSites];
  805. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  806. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  807. }
  808. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  809. {
  810. NSLog(@"[LOG] No External Sites found");
  811. }
  812. #pragma --------------------------------------------------------------------------------------------
  813. #pragma mark ==== Activity ====
  814. #pragma --------------------------------------------------------------------------------------------
  815. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  816. {
  817. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  818. // Reload Activity Data Source
  819. [app.activeActivity reloadDatasource];
  820. }
  821. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  822. {
  823. NSLog(@"[LOG] No Activity found");
  824. }
  825. #pragma --------------------------------------------------------------------------------------------
  826. #pragma mark ==== Notification ====
  827. #pragma --------------------------------------------------------------------------------------------
  828. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  829. {
  830. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  831. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  832. // Order by date
  833. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  834. OCNotifications *notification1 = obj1, *notification2 = obj2;
  835. return [notification2.date compare: notification1.date];
  836. }];
  837. // verify if listOfNotifications is changed
  838. NSString *old = @"", *new = @"";
  839. for (OCNotifications *notification in listOfNotifications)
  840. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  841. for (OCNotifications *notification in appDelegate.listOfNotifications)
  842. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  843. if (![new isEqualToString:old]) {
  844. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  845. // reload Notification view
  846. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  847. }
  848. // Update NavigationBar
  849. if (!_isSelectedMode) {
  850. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  851. }
  852. });
  853. }
  854. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  855. {
  856. // Update NavigationBar
  857. if (!_isSelectedMode)
  858. [self setUINavigationBarDefault];
  859. }
  860. - (void)viewNotification
  861. {
  862. if ([app.listOfNotifications count] > 0) {
  863. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  864. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  865. [self presentViewController:notificationVC animated:YES completion:nil];
  866. }
  867. }
  868. #pragma --------------------------------------------------------------------------------------------
  869. #pragma mark ==== User Profile ====
  870. #pragma --------------------------------------------------------------------------------------------
  871. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  872. {
  873. if (errorCode == 401)
  874. [self changePasswordAccount];
  875. }
  876. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  877. {
  878. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  879. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  880. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  881. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  882. if (avatar)
  883. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  884. else
  885. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  886. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  887. });
  888. }
  889. #pragma --------------------------------------------------------------------------------------------
  890. #pragma mark ==== Capabilities ====
  891. #pragma --------------------------------------------------------------------------------------------
  892. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  893. {
  894. // Change Theming color
  895. [app settingThemingColorBrand];
  896. if (errorCode == 401)
  897. [self changePasswordAccount];
  898. }
  899. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  900. {
  901. // Update capabilities db
  902. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  903. // ------ THEMING -----------------------------------------------------------------------
  904. // Download Theming Background & Change Theming color
  905. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  906. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  907. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  908. if (themingBackground)
  909. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  910. else
  911. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  912. }
  913. dispatch_async(dispatch_get_main_queue(), ^{
  914. [app settingThemingColorBrand];
  915. });
  916. });
  917. // ------ SEARCH ------------------------------------------------------------------------
  918. // Search bar if change version
  919. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  920. [self cancelSearchBar];
  921. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  922. if (capabilities.versionMajor >= 12) {
  923. if (_isRoot)
  924. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  925. else
  926. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  927. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  928. } else {
  929. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  930. self.searchController.searchBar.scopeButtonTitles = nil;
  931. }
  932. _depth = @"0";
  933. });
  934. }
  935. // ------ GET SERVICE SERVER ------------------------------------------------------------
  936. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  937. // Read External Sites
  938. if (capabilities.isExternalSitesServerEnabled) {
  939. metadataNet.action = actionGetExternalSitesServer;
  940. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  941. }
  942. // Read Share
  943. if (capabilities.isFilesSharingAPIEnabled) {
  944. [app.sharesID removeAllObjects];
  945. metadataNet.action = actionReadShareServer;
  946. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  947. }
  948. // Read Notification
  949. metadataNet.action = actionGetNotificationServer;
  950. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  951. // Read User Profile
  952. metadataNet.action = actionGetUserProfile;
  953. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  954. // Read Activity
  955. metadataNet.action = actionGetActivityServer;
  956. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  957. }
  958. #pragma mark -
  959. #pragma --------------------------------------------------------------------------------------------
  960. #pragma mark ==== Request Server Information ====
  961. #pragma --------------------------------------------------------------------------------------------
  962. - (void)requestServerCapabilities
  963. {
  964. // test
  965. if (app.activeAccount.length == 0)
  966. return;
  967. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  968. metadataNet.action = actionGetCapabilities;
  969. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  970. }
  971. #pragma mark -
  972. #pragma --------------------------------------------------------------------------------------------
  973. #pragma mark ==== Middleware Ping ====
  974. #pragma --------------------------------------------------------------------------------------------
  975. - (void)middlewarePing
  976. {
  977. // test
  978. if (app.activeAccount.length == 0)
  979. return;
  980. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  981. metadataNet.action = actionMiddlewarePing;
  982. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  983. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  984. }
  985. #pragma mark -
  986. #pragma --------------------------------------------------------------------------------------------
  987. #pragma mark ==== Download Thumbnail Delegate ====
  988. #pragma --------------------------------------------------------------------------------------------
  989. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  990. {
  991. __block CCCellMain *cell;
  992. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  993. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  994. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  995. cell.file.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  996. if (cell.file.image == nil) {
  997. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  998. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  999. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  1000. });
  1001. }
  1002. }
  1003. }
  1004. #pragma --------------------------------------------------------------------------------------------
  1005. #pragma mark ==== Download ====
  1006. #pragma --------------------------------------------------------------------------------------------
  1007. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1008. {
  1009. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1010. // File do not exists on server, remove in local
  1011. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1012. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  1013. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  1014. if (metadata.directory && serverUrl) {
  1015. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  1016. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  1017. }
  1018. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1019. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1020. }
  1021. if ([selector isEqualToString:selectorLoadViewImage]) {
  1022. dispatch_async(dispatch_get_main_queue(), ^{
  1023. // Updating Detail
  1024. if (app.activeDetail)
  1025. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1026. // Updating Photos
  1027. if (app.activePhotos)
  1028. [app.activePhotos downloadFileFailure:errorCode];
  1029. });
  1030. } else {
  1031. if (errorCode != kCFURLErrorCancelled)
  1032. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1033. }
  1034. [self reloadDatasource:serverUrl selector:selector];
  1035. }
  1036. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1037. {
  1038. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1039. if (metadata == nil)
  1040. return;
  1041. // Download
  1042. if ([selector isEqualToString:selectorDownloadFile]) {
  1043. [self reloadDatasource:serverUrl selector:selector];
  1044. }
  1045. // Synchronized
  1046. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1047. [self reloadDatasource:serverUrl selector:selector];
  1048. }
  1049. // add Favorite
  1050. if ([selector isEqualToString:selectorAddFavorite]) {
  1051. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1052. }
  1053. // encrypted file
  1054. if ([selector isEqualToString:selectorEncryptFile]) {
  1055. [self encryptedFile:metadata];
  1056. }
  1057. // decrypted file
  1058. if ([selector isEqualToString:selectorDecryptFile]) {
  1059. [self decryptedFile:metadata];
  1060. }
  1061. // open View File
  1062. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1063. [self reloadDatasource:serverUrl selector:selector];
  1064. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1065. selector = selectorOpenIn;
  1066. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1067. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1068. selector = selectorOpenIn;
  1069. } else {
  1070. _metadata = metadata;
  1071. if ([self shouldPerformSegue])
  1072. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1073. }
  1074. }
  1075. // addLocal
  1076. if ([selector isEqualToString:selectorAddLocal]) {
  1077. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1078. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1079. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1080. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1081. [self reloadDatasource:serverUrl selector:selector];
  1082. }
  1083. // Open with...
  1084. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1085. [self reloadDatasource:serverUrl selector:selector];
  1086. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1087. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1088. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1089. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1090. _docController.delegate = self;
  1091. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1092. }
  1093. // Save to Photo Album
  1094. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1095. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1096. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1097. // evitiamo il rimando photo
  1098. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1099. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1100. if (image)
  1101. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1102. else
  1103. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1104. }
  1105. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1106. // we avoid the cross-reference video
  1107. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1108. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1109. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1110. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1111. } else {
  1112. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1113. }
  1114. }
  1115. [self reloadDatasource:serverUrl selector:selector];
  1116. }
  1117. // Copy File
  1118. if ([selector isEqualToString:selectorLoadCopy]) {
  1119. [self reloadDatasource:serverUrl selector:selector];
  1120. [self copyFileToPasteboard:metadata];
  1121. }
  1122. // download and view a template
  1123. if ([selector isEqualToString:selectorLoadModelView]) {
  1124. // se è un template aggiorniamo anche nel FileSystem
  1125. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1126. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1127. }
  1128. [self openModel:metadata.model isNew:false];
  1129. [self reloadDatasource:serverUrl selector:selector];
  1130. }
  1131. //download file plist
  1132. if ([selector isEqualToString:selectorLoadPlist]) {
  1133. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1134. long countSelectorLoadPlist = 0;
  1135. for (NSOperation *operation in [app.netQueue operations]) {
  1136. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1137. countSelectorLoadPlist++;
  1138. }
  1139. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1140. dispatch_async(dispatch_get_main_queue(), ^{
  1141. [self reloadDatasource:serverUrl selector:selector];
  1142. });
  1143. }
  1144. });
  1145. }
  1146. //selectorLoadViewImage
  1147. if ([selector isEqualToString:selectorLoadViewImage]) {
  1148. // Detail
  1149. if (app.activeDetail)
  1150. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1151. // Photos
  1152. if (app.activePhotos)
  1153. [app.activePhotos downloadFileSuccess:metadata];
  1154. [self reloadDatasource:serverUrl selector:selector];
  1155. }
  1156. // if exists postselector call self with selectorPost
  1157. if ([selectorPost length] > 0)
  1158. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1159. }
  1160. - (void)downloadSelectedFilesFolders
  1161. {
  1162. NSLog(@"[LOG] Start download selected ...");
  1163. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1164. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1165. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1166. for (tableMetadata *metadata in selectedMetadatas) {
  1167. if ([metadata.type isEqualToString: k_metadataType_file]) {
  1168. if (metadata.directory) {
  1169. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1170. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1171. [[CCSynchronize sharedSynchronize] synchronizedFolder:serverUrl selector:selectorReadFolderWithDownload];
  1172. } else {
  1173. [[CCSynchronize sharedSynchronize] synchronizedFile:metadata selector:selectorReadFileWithDownload];
  1174. }
  1175. }
  1176. }
  1177. [_hud hideHud];
  1178. });
  1179. [self tableViewSelect:NO];
  1180. }
  1181. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1182. {
  1183. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1184. for (tableMetadata *metadata in metadatas) {
  1185. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1186. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1187. metadataNet.action = actionDownloadFile;
  1188. metadataNet.downloadData = NO;
  1189. metadataNet.downloadPlist = YES;
  1190. metadataNet.fileID = metadata.fileID;
  1191. metadataNet.selector = selectorLoadPlist;
  1192. metadataNet.serverUrl = serverUrl;
  1193. metadataNet.session = k_download_session_foreground;
  1194. metadataNet.taskStatus = k_taskStatusResume;
  1195. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1196. //[[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selectorLoadPlist selectorPost:nil session:k_download_session_foreground taskStatus:k_taskStatusResume delegate:self];
  1197. }
  1198. }
  1199. }
  1200. #pragma --------------------------------------------------------------------------------------------
  1201. #pragma mark ===== Upload new Photos/Videos =====
  1202. #pragma --------------------------------------------------------------------------------------------
  1203. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1204. {
  1205. // Auto Upload
  1206. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1207. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1208. // ONLY BACKGROUND
  1209. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1210. } else {
  1211. // ONLY FOREFROUND
  1212. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1213. }
  1214. }
  1215. // Read File test do not exists
  1216. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1217. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1218. // reUpload
  1219. if (metadata)
  1220. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1221. }
  1222. // Print error
  1223. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1224. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1225. }
  1226. [self reloadDatasource:serverUrl selector:selector];
  1227. }
  1228. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1229. {
  1230. // Auto Upload
  1231. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1232. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1233. // ONLY BACKGROUND
  1234. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1235. } else {
  1236. // ONLY FOREFROUND
  1237. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1238. }
  1239. }
  1240. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1241. [self readFolderWithForced:YES serverUrl:serverUrl];
  1242. } else {
  1243. [self reloadDatasource:serverUrl selector:selector];
  1244. }
  1245. }
  1246. //
  1247. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1248. //
  1249. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1250. {
  1251. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1252. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1253. });
  1254. }
  1255. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1256. {
  1257. NSArray *assets = [arguments objectAtIndex:0];
  1258. NSString *serverUrl = [arguments objectAtIndex:1];
  1259. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1260. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1261. NSString *session = [arguments objectAtIndex:4];
  1262. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1263. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1264. // Create the folder for Photos & if request the subfolders
  1265. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1266. return;
  1267. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1268. for (PHAsset *asset in assets) {
  1269. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1270. NSDate *assetDate = asset.creationDate;
  1271. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1272. // Create serverUrl if use sub folder
  1273. if (useSubFolder) {
  1274. [formatter setDateFormat:@"yyyy"];
  1275. NSString *yearString = [formatter stringFromDate:assetDate];
  1276. [formatter setDateFormat:@"MM"];
  1277. NSString *monthString = [formatter stringFromDate:assetDate];
  1278. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1279. }
  1280. // Check if is in upload
  1281. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1282. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1283. if ([isRecordInSessions count] > 0) {
  1284. // next upload
  1285. continue;
  1286. } else {
  1287. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1288. if (cryptated) {
  1289. metadataNet.action = actionUploadAsset;
  1290. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1291. metadataNet.cryptated = cryptated;
  1292. metadataNet.fileName = fileName;
  1293. metadataNet.priority = NSOperationQueuePriorityNormal;
  1294. metadataNet.session = session;
  1295. metadataNet.selector = selectorUploadFile;
  1296. metadataNet.selectorPost = nil;
  1297. metadataNet.serverUrl = serverUrl;
  1298. metadataNet.taskStatus = k_taskStatusResume;
  1299. } else {
  1300. metadataNet.action = actionReadFile;
  1301. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1302. metadataNet.cryptated = cryptated;
  1303. metadataNet.fileName = fileName;
  1304. metadataNet.priority = NSOperationQueuePriorityNormal;
  1305. metadataNet.session = session;
  1306. metadataNet.selector = selectorReadFileUploadFile;
  1307. metadataNet.serverUrl = serverUrl;
  1308. }
  1309. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1310. }
  1311. }
  1312. }
  1313. #pragma --------------------------------------------------------------------------------------------
  1314. #pragma mark ==== Read File ====
  1315. #pragma --------------------------------------------------------------------------------------------
  1316. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1317. {
  1318. // Read Folder
  1319. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1320. [self readFolderWithForced:NO serverUrl:metadataNet.serverUrl];
  1321. }
  1322. // UploadFile
  1323. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1324. // File not exists
  1325. if (errorCode == 404) {
  1326. metadataNet.action = actionUploadAsset;
  1327. metadataNet.errorCode = 0;
  1328. metadataNet.selector = selectorUploadFile;
  1329. metadataNet.selectorPost = nil;
  1330. metadataNet.taskStatus = k_taskStatusResume;
  1331. if ([metadataNet.session containsString:@"wwan"])
  1332. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1333. else
  1334. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1335. } else {
  1336. // error ho many retry befor notification and go to on next asses
  1337. if (metadataNet.errorRetry < 3) {
  1338. // Retry read file
  1339. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1340. } else {
  1341. // STOP check file, view message error
  1342. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1343. }
  1344. }
  1345. }
  1346. }
  1347. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1348. {
  1349. // Read Folder
  1350. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1351. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1352. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1353. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1354. }
  1355. }
  1356. // UploadFile
  1357. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1358. metadataNet.action = actionUploadAsset;
  1359. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1360. metadataNet.selector = selectorUploadFile;
  1361. metadataNet.selectorPost = nil;
  1362. metadataNet.taskStatus = k_taskStatusResume;
  1363. if ([metadataNet.session containsString:@"wwan"])
  1364. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1365. else
  1366. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1367. }
  1368. }
  1369. - (void)readFileReloadFolder
  1370. {
  1371. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1372. metadataNet.action = actionReadFile;
  1373. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1374. metadataNet.selector = selectorReadFileReloadFolder;
  1375. metadataNet.serverUrl = _serverUrl;
  1376. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1377. }
  1378. #pragma --------------------------------------------------------------------------------------------
  1379. #pragma mark ==== Read Folder ====
  1380. #pragma --------------------------------------------------------------------------------------------
  1381. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1382. {
  1383. // verify active user
  1384. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1385. [_hud hideHud];
  1386. [_refreshControl endRefreshing];
  1387. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1388. if (message && [record.account isEqualToString:metadataNet.account])
  1389. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1390. [self reloadDatasource:metadataNet.serverUrl selector:metadataNet.selector];
  1391. if (errorCode == 401)
  1392. [self changePasswordAccount];
  1393. }
  1394. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1395. {
  1396. // verify active user
  1397. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1398. if (![record.account isEqualToString:metadataNet.account])
  1399. return;
  1400. // save father e update permission
  1401. if(!_isSearchMode)
  1402. _fatherPermission = permissions;
  1403. NSArray *recordsInSessions;
  1404. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1405. if (_isSearchMode) {
  1406. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1407. } else {
  1408. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:etag];
  1409. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1410. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1411. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1412. }
  1413. for (tableMetadata *metadata in metadatas) {
  1414. // type of file
  1415. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1416. // if crypto do not insert
  1417. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1418. // verify if the record encrypted has plist + crypto
  1419. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1420. BOOL isCryptoComplete = NO;
  1421. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1422. for (tableMetadata *completeMetadata in metadatas) {
  1423. if (completeMetadata.cryptated == NO) continue;
  1424. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1425. isCryptoComplete = YES;
  1426. break;
  1427. }
  1428. }
  1429. if (isCryptoComplete == NO) continue;
  1430. }
  1431. // verify if the record is in download/upload progress
  1432. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1433. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1434. // is in Download or Upload
  1435. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1436. continue;
  1437. }
  1438. }
  1439. // Insert in Array
  1440. [metadatasToInsertInDB addObject:metadata];
  1441. }
  1442. // insert in Database
  1443. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB activeUrl:app.activeUrl serverUrl:metadataNet.serverUrl];
  1444. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1445. // read plist
  1446. if (!_isSearchMode)
  1447. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1448. // File is changed ??
  1449. if (!_isSearchMode && metadatasToInsertInDB)
  1450. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1451. });
  1452. // Search Mode
  1453. if (_isSearchMode)
  1454. [self reloadDatasource:metadataNet.serverUrl selector:metadataNet.selector];
  1455. // this is the same directory
  1456. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1457. // reload
  1458. [self reloadDatasource:metadataNet.serverUrl selector:metadataNet.selector];
  1459. // stoprefresh
  1460. [_refreshControl endRefreshing];
  1461. // Enable change user
  1462. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1463. [_hud hideHud];
  1464. }
  1465. }
  1466. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1467. {
  1468. // init control
  1469. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1470. [_hud hideHud];
  1471. [_refreshControl endRefreshing];
  1472. return;
  1473. }
  1474. // Search Mode
  1475. if (_isSearchMode) {
  1476. if (forced) {
  1477. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1478. _searchFileName = @""; // forced reload searchg
  1479. }
  1480. [self updateSearchResultsForSearchController:self.searchController];
  1481. return;
  1482. }
  1483. BOOL isDirectoryOutOfDate = true;
  1484. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  1485. if (directory.dateReadDirectory) {
  1486. // Is Directory Out Of Date ?
  1487. NSDateComponents *dateComponents = [NSDateComponents new];
  1488. [dateComponents setWeekday:k_dayForceReadFolder];
  1489. NSCalendar *calendar = [NSCalendar currentCalendar];
  1490. NSDate *datePlus = [calendar dateByAddingComponents:dateComponents toDate:directory.dateReadDirectory options:0];
  1491. NSDate *now = [NSDate date];
  1492. // usa la Cache se richiesto e se la data è entro X giorni dall'ultima volta che l'hai letta.
  1493. if ([now compare:datePlus] == NSOrderedDescending)
  1494. isDirectoryOutOfDate = true;
  1495. else
  1496. isDirectoryOutOfDate = false;
  1497. }
  1498. if (isDirectoryOutOfDate || forced) {
  1499. if (_refreshControl.isRefreshing == NO)
  1500. [_hud visibleIndeterminateHud];
  1501. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1502. metadataNet.action = actionReadFolder;
  1503. metadataNet.date = [NSDate date];
  1504. metadataNet.directoryID = directory.directoryID;
  1505. metadataNet.priority = NSOperationQueuePriorityHigh;
  1506. metadataNet.selector = selectorReadFolder;
  1507. metadataNet.serverUrl = serverUrl;
  1508. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1509. }
  1510. }
  1511. #pragma mark -
  1512. #pragma --------------------------------------------------------------------------------------------
  1513. #pragma mark ===== Search =====
  1514. #pragma --------------------------------------------------------------------------------------------
  1515. -(void)searchStartTimer
  1516. {
  1517. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth date:nil selector:selectorSearch delegate:self];
  1518. _noFilesSearchTitle = @"";
  1519. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1520. [self.tableView reloadEmptyDataSet];
  1521. }
  1522. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1523. {
  1524. _isSearchMode = YES;
  1525. [self deleteRefreshControl];
  1526. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1527. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1528. _searchFileName = fileName;
  1529. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12 && ![_depth isEqualToString:@"0"]) {
  1530. [_timerWaitInput invalidate];
  1531. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1532. } else {
  1533. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1534. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1535. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1536. [_searchResultMetadatas removeAllObjects];
  1537. for (tableMetadata *record in records)
  1538. [_searchResultMetadatas addObject:record];
  1539. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1540. metadataNet.account = app.activeAccount;
  1541. metadataNet.action = actionUploadTemplate;
  1542. metadataNet.directoryID = directoryID;
  1543. metadataNet.selector = selectorSearch;
  1544. metadataNet.serverUrl = _serverUrl;
  1545. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1546. }
  1547. }
  1548. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1549. [self reloadDatasource];
  1550. }
  1551. }
  1552. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1553. {
  1554. [self cancelSearchBar];
  1555. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1556. }
  1557. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1558. {
  1559. _searchFileName = @"";
  1560. if (message)
  1561. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1562. }
  1563. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1564. {
  1565. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1566. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1567. }
  1568. - (void)cancelSearchBar
  1569. {
  1570. if (self.searchController.active) {
  1571. [self.searchController setActive:NO];
  1572. [self createRefreshControl];
  1573. _isSearchMode = NO;
  1574. _searchFileName = @"";
  1575. _dateReadDataSource = nil;
  1576. _searchResultMetadatas = [NSMutableArray new];
  1577. [self reloadDatasource];
  1578. }
  1579. }
  1580. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1581. {
  1582. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1583. self.searchController.searchBar.placeholder = title;
  1584. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1585. _depth = @"0";
  1586. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1587. _depth = @"1";
  1588. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1589. _depth = @"infinity";
  1590. _searchFileName = @"";
  1591. [self updateSearchResultsForSearchController:self.searchController];
  1592. }
  1593. #pragma mark -
  1594. #pragma --------------------------------------------------------------------------------------------
  1595. #pragma mark ===== Delete File or Folder =====
  1596. #pragma --------------------------------------------------------------------------------------------
  1597. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1598. {
  1599. [self deleteFileOrFolderSuccess:metadataNet];
  1600. }
  1601. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1602. {
  1603. [_queueSelector removeObject:metadataNet.selector];
  1604. if ([_queueSelector count] == 0) {
  1605. [_hud hideHud];
  1606. if (_isSearchMode)
  1607. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1608. else
  1609. [self reloadDatasource:metadataNet.serverUrl selector:metadataNet.selector];
  1610. // next
  1611. if ([_selectedMetadatas count] > 0) {
  1612. [_selectedMetadatas removeObjectAtIndex:0];
  1613. if ([_selectedMetadatas count] > 0)
  1614. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1615. }
  1616. }
  1617. }
  1618. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1619. {
  1620. if (metadata.cryptated) {
  1621. [_queueSelector addObject:selectorDeleteCrypto];
  1622. [_queueSelector addObject:selectorDeletePlist];
  1623. } else {
  1624. [_queueSelector addObject:selectorDelete];
  1625. }
  1626. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1627. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1628. }
  1629. - (void)deleteSelectionFile
  1630. {
  1631. [_selectedMetadatas removeAllObjects];
  1632. [_queueSelector removeAllObjects];
  1633. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1634. _numSelectedMetadatas = [_selectedMetadatas count];
  1635. if ([_selectedMetadatas count] > 0)
  1636. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1637. [self tableViewSelect:NO];
  1638. }
  1639. - (void)deleteFile
  1640. {
  1641. [_selectedMetadatas removeAllObjects];
  1642. [_queueSelector removeAllObjects];
  1643. _numSelectedMetadatas = 1;
  1644. [_selectedMetadatas addObject:_metadata];
  1645. if ([_selectedMetadatas count] > 0)
  1646. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1647. [self tableViewSelect:NO];
  1648. }
  1649. #pragma --------------------------------------------------------------------------------------------
  1650. #pragma mark ===== Rename / Move =====
  1651. #pragma --------------------------------------------------------------------------------------------
  1652. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1653. {
  1654. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1655. }
  1656. - (void)renameFile:(NSArray *)arguments
  1657. {
  1658. tableMetadata* metadata = [arguments objectAtIndex:0];
  1659. NSString *fileName = [arguments objectAtIndex:1];
  1660. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1661. }
  1662. - (void)renameNote:(NSArray *)arguments
  1663. {
  1664. tableMetadata* metadata = [arguments objectAtIndex:0];
  1665. NSString *fileName = [arguments objectAtIndex:1];
  1666. CCTemplates *templates = [[CCTemplates alloc] init];
  1667. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1668. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1669. if (fileNameModel) {
  1670. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1671. metadataNet.action = actionUploadTemplate;
  1672. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1673. metadataNet.fileNamePrint = fileName;
  1674. metadataNet.etag = metadata.etag;
  1675. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1676. metadataNet.session = k_upload_session_foreground;
  1677. metadataNet.taskStatus = k_taskStatusResume;
  1678. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1679. }
  1680. }
  1681. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1682. {
  1683. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1684. [_hud hideHud];
  1685. if (message)
  1686. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1687. [_selectedMetadatas removeAllObjects];
  1688. [_queueSelector removeAllObjects];
  1689. }
  1690. }
  1691. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1692. {
  1693. [_queueSelector removeObject:metadataNet.selector];
  1694. if ([_queueSelector count] == 0) {
  1695. [_hud hideHud];
  1696. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1697. NSString *directoryID = metadataNet.directoryID;
  1698. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1699. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1700. // FILE -> Metadata
  1701. if (metadataNet.directory == NO) {
  1702. // move metadata
  1703. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1704. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1705. }
  1706. // DIRECTORY -> Directory - CCMetadata
  1707. if (metadataNet.directory == YES) {
  1708. // delete all dir / subdir
  1709. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1710. // move metadata
  1711. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1712. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1713. // Add new directory
  1714. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1715. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1716. }
  1717. // reload Datasource
  1718. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1719. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1720. else
  1721. [self reloadDatasource];
  1722. // Next file
  1723. [_selectedMetadatas removeObjectAtIndex:0];
  1724. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1725. }
  1726. }
  1727. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1728. {
  1729. if ([_selectedMetadatas count] > 0) {
  1730. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1731. // Plain
  1732. if (metadata.cryptated == NO) {
  1733. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1734. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1735. if(!error) {
  1736. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1737. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1738. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1739. }];
  1740. [alert addAction:ok];
  1741. [self presentViewController:alert animated:YES completion:nil];
  1742. });
  1743. return;
  1744. }
  1745. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1746. metadataNet.action = actionMoveFileOrFolder;
  1747. metadataNet.directory = metadata.directory;
  1748. metadataNet.fileID = metadata.fileID;
  1749. metadataNet.directoryID = metadata.directoryID;
  1750. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1751. metadataNet.fileName = metadata.fileName;
  1752. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1753. metadataNet.fileNameTo = metadata.fileName;
  1754. metadataNet.etag = metadata.etag;
  1755. metadataNet.selector = selectorMove;
  1756. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1757. metadataNet.serverUrlTo = serverUrlTo;
  1758. [_queueSelector addObject:metadataNet.selector];
  1759. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1760. }
  1761. // cyptated
  1762. if (metadata.cryptated == YES) {
  1763. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1764. metadataNet.action = actionMoveFileOrFolder;
  1765. metadataNet.directory = metadata.directory;
  1766. metadataNet.fileID = metadata.fileID;
  1767. metadataNet.directoryID = metadata.directoryID;
  1768. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1769. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1770. metadataNet.etag = metadata.etag;
  1771. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1772. metadataNet.serverUrlTo = serverUrlTo;
  1773. // data
  1774. metadataNet.fileName = metadata.fileNameData;
  1775. metadataNet.fileNameTo = metadata.fileNameData;
  1776. metadataNet.selector = selectorMoveCrypto;
  1777. [_queueSelector addObject:metadataNet.selector];
  1778. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1779. // plist
  1780. metadataNet.fileName = metadata.fileName;
  1781. metadataNet.fileNameTo = metadata.fileName;
  1782. metadataNet.selector = selectorMovePlist;
  1783. [_queueSelector addObject:metadataNet.selector];
  1784. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1785. }
  1786. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1787. }
  1788. }
  1789. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1790. {
  1791. [_selectedMetadatas removeAllObjects];
  1792. [_queueSelector removeAllObjects];
  1793. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1794. _numSelectedMetadatas = [_selectedMetadatas count];
  1795. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1796. [self tableViewSelect:NO];
  1797. }
  1798. - (void)moveOpenWindow:(NSArray *)indexPaths
  1799. {
  1800. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1801. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1802. viewController.delegate = self;
  1803. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1804. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1805. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1806. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1807. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1808. viewController.networkingOperationQueue = app.netQueue;
  1809. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1810. [self presentViewController:navigationController animated:YES completion:nil];
  1811. }
  1812. #pragma --------------------------------------------------------------------------------------------
  1813. #pragma mark ===== Create folder =====
  1814. #pragma --------------------------------------------------------------------------------------------
  1815. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1816. {
  1817. [_hud hideHud];
  1818. if (message)
  1819. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1820. }
  1821. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1822. {
  1823. [_hud hideHud];
  1824. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1825. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1826. // Load Folder or the Datasource
  1827. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1828. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1829. } else {
  1830. [self reloadDatasource:metadataNet.serverUrl selector:metadataNet.selector];
  1831. }
  1832. }
  1833. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1834. {
  1835. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1836. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1837. if (![fileNameFolder length]) return;
  1838. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1839. else metadataNet.serverUrl = _serverUrl;
  1840. metadataNet.action = actionCreateFolder;
  1841. if (autoUploadDirectory)
  1842. metadataNet.options = @"folderAutoUpload";
  1843. metadataNet.fileName = fileNameFolder;
  1844. metadataNet.selector = selectorCreateFolder;
  1845. metadataNet.selectorPost = selectorReadFolderForced;
  1846. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1847. if (!autoUploadDirectory)
  1848. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1849. }
  1850. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1851. {
  1852. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1853. NSString *fileNamePlist;
  1854. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1855. if (![fileNameFolder length]) return;
  1856. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1857. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1858. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1859. // Create folder
  1860. metadataNet.action = actionCreateFolder;
  1861. metadataNet.fileName = fileNamePlist;
  1862. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1863. metadataNet.selector = selectorCreateFolder;
  1864. metadataNet.serverUrl = _serverUrl;
  1865. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1866. // upload plist file
  1867. metadataNet.action = actionUploadOnlyPlist;
  1868. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1869. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1870. metadataNet.selectorPost = selectorReadFolderForced;
  1871. metadataNet.serverUrl = _serverUrl;
  1872. metadataNet.session = k_upload_session_foreground;
  1873. metadataNet.taskStatus = k_taskStatusResume;
  1874. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1875. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1876. }
  1877. - (void)createFolderAutoUpload
  1878. {
  1879. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1880. [self createFolder:autoUploadFileName autoUploadDirectory:YES];
  1881. }
  1882. #pragma --------------------------------------------------------------------------------------------
  1883. #pragma mark ===== Encrypted / Decrypted Folder =====
  1884. #pragma --------------------------------------------------------------------------------------------
  1885. - (void)encyptedDecryptedFolder
  1886. {
  1887. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1888. if (_metadata.cryptated) {
  1889. // DECRYPTED
  1890. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1891. //-------------------------- RENAME -------------------------------------------//
  1892. metadataNet.action = actionMoveFileOrFolder;
  1893. metadataNet.fileID = _metadata.fileID;
  1894. metadataNet.fileName = _metadata.fileNameData;
  1895. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1896. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1897. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1898. metadataNet.selector = selectorRename;
  1899. metadataNet.serverUrl = serverUrl;
  1900. metadataNet.serverUrlTo = serverUrl;
  1901. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1902. //-------------------------- DELETE -------------------------------------------//
  1903. metadataNet.action = actionDeleteFileDirectory;
  1904. metadataNet.fileID = _metadata.fileID;
  1905. metadataNet.fileName = _metadata.fileName;
  1906. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1907. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1908. metadataNet.selector = selectorDeletePlist;
  1909. metadataNet.selectorPost = selectorReadFolderForced;
  1910. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1911. } else {
  1912. // ENCRYPTED
  1913. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1914. // Create File Plist
  1915. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1916. //-------------------------- RENAME -------------------------------------------//
  1917. metadataNet.action = actionMoveFileOrFolder;
  1918. metadataNet.fileID = _metadata.fileID;
  1919. metadataNet.fileName = _metadata.fileName;
  1920. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1921. metadataNet.fileNameTo = fileNameCrypto;
  1922. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1923. metadataNet.selector = selectorRename;
  1924. metadataNet.serverUrl = serverUrl;
  1925. metadataNet.serverUrlTo = serverUrl;
  1926. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1927. //-------------------------- UPLOAD -------------------------------------------//
  1928. metadataNet.action = actionUploadOnlyPlist;
  1929. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1930. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1931. metadataNet.selectorPost = selectorReadFolderForced;
  1932. metadataNet.serverUrl = serverUrl;
  1933. metadataNet.session = k_upload_session_foreground;
  1934. metadataNet.taskStatus = k_taskStatusResume;
  1935. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1936. }
  1937. }
  1938. #pragma --------------------------------------------------------------------------------------------
  1939. #pragma mark ===== Encrypted/Decrypted File =====
  1940. #pragma --------------------------------------------------------------------------------------------
  1941. - (void)encryptedSelectedFiles
  1942. {
  1943. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1944. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1945. for (tableMetadata *metadata in selectedMetadatas) {
  1946. if (metadata.cryptated == NO && metadata.directory == NO)
  1947. [metadatas addObject:metadata];
  1948. }
  1949. if ([metadatas count] > 0) {
  1950. NSLog(@"[LOG] Start encrypted selected files ...");
  1951. for (tableMetadata* metadata in metadatas) {
  1952. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1953. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1954. }
  1955. }
  1956. [self tableViewSelect:NO];
  1957. }
  1958. - (void)decryptedSelectedFiles
  1959. {
  1960. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1961. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1962. for (tableMetadata *metadata in selectedMetadatas) {
  1963. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1964. [metadatas addObject:metadata];
  1965. }
  1966. if ([metadatas count] > 0) {
  1967. NSLog(@"[LOG] Start decrypted selected files ...");
  1968. for (tableMetadata* metadata in metadatas) {
  1969. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1970. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1971. }
  1972. }
  1973. [self tableViewSelect:NO];
  1974. }
  1975. - (void)cmdEncryptedDecryptedFile
  1976. {
  1977. NSString *selector;
  1978. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1979. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1980. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1981. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1982. }
  1983. - (void)encryptedFile:(tableMetadata *)metadata
  1984. {
  1985. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1986. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1987. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1988. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1989. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1990. dispatch_async(dispatch_get_main_queue(), ^{
  1991. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1992. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1993. });
  1994. } else {
  1995. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1996. }
  1997. }
  1998. - (void)decryptedFile:(tableMetadata *)metadata
  1999. {
  2000. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  2001. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  2002. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  2003. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  2004. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2005. dispatch_async(dispatch_get_main_queue(), ^{
  2006. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2007. [self performSelector:@selector(reloadDatasource) withObject:nil];
  2008. });
  2009. } else {
  2010. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2011. }
  2012. }
  2013. #pragma --------------------------------------------------------------------------------------------
  2014. #pragma mark ===== Progress & Task Button =====
  2015. #pragma --------------------------------------------------------------------------------------------
  2016. - (void)triggerProgressTask:(NSNotification *)notification
  2017. {
  2018. NSDictionary *dict = notification.userInfo;
  2019. NSString *fileID = [dict valueForKey:@"fileID"];
  2020. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  2021. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  2022. float progress = [[dict valueForKey:@"progress"] floatValue];
  2023. // Check
  2024. if (!fileID)
  2025. return;
  2026. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  2027. if (![serverUrl isEqualToString:_serverUrl])
  2028. return;
  2029. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  2030. if (indexPath) {
  2031. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  2032. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  2033. else cell.progressView.progressTintColor = [UIColor blackColor];
  2034. cell.progressView.hidden = NO;
  2035. [cell.progressView setProgress:progress];
  2036. }
  2037. if (progress == 0)
  2038. [self.navigationController cancelCCProgress];
  2039. else
  2040. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  2041. }
  2042. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  2043. {
  2044. UITouch * touch = [[event allTouches] anyObject];
  2045. CGPoint location = [touch locationInView:self.tableView];
  2046. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2047. if (indexPath) {
  2048. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2049. if (metadata)
  2050. [self reloadTaskButton:metadata];
  2051. }
  2052. }
  2053. - (void)reloadTaskButton:(tableMetadata *)metadata
  2054. {
  2055. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2056. __block NSURLSessionTask *findTask;
  2057. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2058. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2059. NSString *fileID = metadata.fileID;
  2060. // DOWNLOAD
  2061. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2062. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2063. for (NSURLSessionUploadTask *task in downloadTasks)
  2064. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2065. findTask = task;
  2066. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2067. [task cancel];
  2068. }
  2069. if (!findTask) {
  2070. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2071. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2072. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2073. }
  2074. }];
  2075. }
  2076. // UPLOAD
  2077. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2078. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2079. for (NSURLSessionUploadTask *task in uploadTasks)
  2080. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2081. findTask = task;
  2082. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2083. [task cancel];
  2084. }
  2085. if (!findTask) {
  2086. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2087. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2088. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2089. }
  2090. }];
  2091. }
  2092. }
  2093. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2094. {
  2095. UITouch * touch = [[event allTouches] anyObject];
  2096. CGPoint location = [touch locationInView:self.tableView];
  2097. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2098. if (indexPath) {
  2099. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2100. if (metadata)
  2101. [self cancelTaskButton:metadata reloadTable:YES];
  2102. }
  2103. }
  2104. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2105. {
  2106. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2107. __block NSURLSessionTask *findTask;
  2108. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2109. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2110. NSString *fileID = metadata.fileID;
  2111. // DOWNLOAD
  2112. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2113. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2114. for (NSURLSessionTask *task in downloadTasks)
  2115. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2116. findTask = task;
  2117. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2118. [task cancel];
  2119. }
  2120. if (!findTask) {
  2121. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2122. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2123. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2124. }
  2125. }];
  2126. }
  2127. // UPLOAD
  2128. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2129. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2130. for (NSURLSessionUploadTask *task in uploadTasks)
  2131. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2132. findTask = task;
  2133. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2134. [task cancel];
  2135. }
  2136. if (!findTask) {
  2137. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2138. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2139. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2140. }
  2141. }];
  2142. }
  2143. }
  2144. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2145. {
  2146. UITouch * touch = [[event allTouches] anyObject];
  2147. CGPoint location = [touch locationInView:self.tableView];
  2148. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2149. if (indexPath) {
  2150. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2151. if (metadata)
  2152. [self stopTaskButton:metadata];
  2153. }
  2154. }
  2155. - (void)stopTaskButton:(tableMetadata *)metadata
  2156. {
  2157. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2158. __block NSURLSessionTask *findTask;
  2159. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2160. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2161. NSString *fileID = metadata.fileID;
  2162. // UPLOAD
  2163. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2164. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2165. for (NSURLSessionUploadTask *task in uploadTasks)
  2166. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2167. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2168. findTask = task;
  2169. [task cancel];
  2170. }
  2171. if (!findTask) {
  2172. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2173. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2174. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2175. }
  2176. }];
  2177. }
  2178. }
  2179. #pragma --------------------------------------------------------------------------------------------
  2180. #pragma mark ===== Shared =====
  2181. #pragma --------------------------------------------------------------------------------------------
  2182. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2183. {
  2184. [_hud hideHud];
  2185. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2186. // change account ?
  2187. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2188. if([record.account isEqualToString:metadataNet.account] == NO)
  2189. return;
  2190. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2191. if (result) {
  2192. appDelegate.sharesLink = result[0];
  2193. appDelegate.sharesUserAndGroup = result[1];
  2194. }
  2195. // Notify Shares View
  2196. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2197. if (openWindow) {
  2198. if (_shareOC) {
  2199. [_shareOC reloadData];
  2200. } else {
  2201. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2202. // Apriamo la view
  2203. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2204. _shareOC.delegate = self;
  2205. _shareOC.metadata = metadata;
  2206. _shareOC.serverUrl = metadataNet.serverUrl;
  2207. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2208. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2209. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2210. [self presentViewController:_shareOC animated:YES completion:nil];
  2211. }
  2212. }
  2213. [self tableViewReload];
  2214. }
  2215. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2216. {
  2217. [_hud hideHud];
  2218. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2219. if (_shareOC)
  2220. [_shareOC reloadData];
  2221. [self tableViewReload];
  2222. if (errorCode == 401)
  2223. [self changePasswordAccount];
  2224. }
  2225. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2226. {
  2227. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2228. metadataNet.action = actionShare;
  2229. metadataNet.fileID = metadata.fileID;
  2230. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2231. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2232. metadataNet.password = password;
  2233. metadataNet.selector = selectorShare;
  2234. metadataNet.serverUrl = serverUrl;
  2235. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2236. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2237. }
  2238. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2239. {
  2240. [_hud hideHud];
  2241. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2242. // rimuoviamo la condivisione da db
  2243. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2244. if (result) {
  2245. appDelegate.sharesLink = result[0];
  2246. appDelegate.sharesUserAndGroup = result[1];
  2247. }
  2248. if (_shareOC)
  2249. [_shareOC reloadData];
  2250. [self tableViewReload];
  2251. }
  2252. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2253. {
  2254. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2255. metadataNet.action = actionUnShare;
  2256. metadataNet.fileID = metadata.fileID;
  2257. metadataNet.fileName = metadata.fileName;
  2258. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2259. metadataNet.selector = selectorUnshare;
  2260. metadataNet.serverUrl = serverUrl;
  2261. metadataNet.share = share;
  2262. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2263. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2264. }
  2265. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2266. {
  2267. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2268. metadataNet.action = actionUpdateShare;
  2269. metadataNet.fileID = metadata.fileID;
  2270. metadataNet.expirationTime = expirationTime;
  2271. metadataNet.password = password;
  2272. metadataNet.selector = selectorUpdateShare;
  2273. metadataNet.serverUrl = serverUrl;
  2274. metadataNet.share = share;
  2275. metadataNet.sharePermission = permission;
  2276. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2277. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2278. }
  2279. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2280. {
  2281. [_hud hideHud];
  2282. if (_shareOC)
  2283. [_shareOC reloadUserAndGroup:items];
  2284. }
  2285. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2286. {
  2287. [_hud hideHud];
  2288. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2289. }
  2290. - (void)getUserAndGroup:(NSString *)find
  2291. {
  2292. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2293. metadataNet.action = actionGetUserAndGroup;
  2294. metadataNet.options = find;
  2295. metadataNet.selector = selectorGetUserAndGroup;
  2296. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2297. [_hud visibleIndeterminateHud];
  2298. }
  2299. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2300. {
  2301. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2302. metadataNet.action = actionShareWith;
  2303. metadataNet.fileID = metadata.fileID;
  2304. metadataNet.directoryID = directoryID;
  2305. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2306. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2307. metadataNet.serverUrl = serverUrl;
  2308. metadataNet.selector = selectorShare;
  2309. metadataNet.share = user;
  2310. metadataNet.shareeType = shareeType;
  2311. metadataNet.sharePermission = permission;
  2312. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2313. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2314. }
  2315. - (void)openWindowShare:(tableMetadata *)metadata
  2316. {
  2317. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2318. metadataNet.action = actionReadShareServer;
  2319. metadataNet.fileID = metadata.fileID;
  2320. metadataNet.fileName = metadata.fileName;
  2321. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2322. metadataNet.selector = selectorOpenWindowShare;
  2323. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2324. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2325. [_hud visibleIndeterminateHud];
  2326. }
  2327. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2328. {
  2329. CGPoint location = [tapGesture locationInView:self.tableView];
  2330. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2331. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2332. if (metadata)
  2333. [self openWindowShare:metadata];
  2334. }
  2335. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2336. {
  2337. CGPoint location = [tapGesture locationInView:self.tableView];
  2338. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2339. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2340. if (metadata) {
  2341. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2342. vc.metadata = metadata;
  2343. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2344. [self presentViewController:vc animated:YES completion:nil];
  2345. }
  2346. }
  2347. #pragma --------------------------------------------------------------------------------------------
  2348. #pragma mark ===== Favorite =====
  2349. #pragma --------------------------------------------------------------------------------------------
  2350. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2351. {
  2352. _dateReadDataSource = nil;
  2353. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2354. if (_isSearchMode)
  2355. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2356. else
  2357. [self reloadDatasource:metadataNet.serverUrl selector:metadataNet.selector];
  2358. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2359. if (metadata.directory && metadata.favorite) {
  2360. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2361. [app.activeFavorites addFavoriteFolder:dir];
  2362. }
  2363. }
  2364. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2365. {
  2366. }
  2367. - (void)addFavorite:(tableMetadata *)metadata
  2368. {
  2369. if (metadata.directory) {
  2370. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2371. } else {
  2372. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2373. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2374. }
  2375. }
  2376. - (void)removeFavorite:(tableMetadata *)metadata
  2377. {
  2378. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2379. }
  2380. #pragma --------------------------------------------------------------------------------------------
  2381. #pragma mark ===== Local =====
  2382. #pragma --------------------------------------------------------------------------------------------
  2383. - (void)addLocal:(tableMetadata *)metadata
  2384. {
  2385. if (metadata.errorPasscode || !metadata.uuid) return;
  2386. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2387. if ([metadata.type isEqualToString: k_metadataType_file])
  2388. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2389. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2390. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2391. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2392. }
  2393. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2394. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2395. }
  2396. #pragma --------------------------------------------------------------------------------------------
  2397. #pragma mark ===== Open in... =====
  2398. #pragma --------------------------------------------------------------------------------------------
  2399. - (void)openIn:(tableMetadata *)metadata
  2400. {
  2401. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2402. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2403. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2404. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2405. }
  2406. #pragma --------------------------------------------------------------------------------------------
  2407. #pragma mark ===== Remove Local File =====
  2408. #pragma --------------------------------------------------------------------------------------------
  2409. - (void)removeLocalFile:(tableMetadata *)metadata
  2410. {
  2411. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2412. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2413. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2414. [self reloadDatasource:serverUrl selector:nil];
  2415. }
  2416. #pragma --------------------------------------------------------------------------------------------
  2417. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2418. #pragma --------------------------------------------------------------------------------------------
  2419. - (void)orderTable:(NSString *)order
  2420. {
  2421. [CCUtility setOrderSettings:order];
  2422. // Clear data-read of DataSource
  2423. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2424. }
  2425. - (void)ascendingTable:(BOOL)ascending
  2426. {
  2427. [CCUtility setAscendingSettings:ascending];
  2428. // Clear data-read of DataSource
  2429. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2430. }
  2431. - (void)directoryOnTop:(BOOL)directoryOnTop
  2432. {
  2433. [CCUtility setDirectoryOnTop:directoryOnTop];
  2434. // Clear data-read of DataSource
  2435. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2436. }
  2437. - (void)tableGroupBy:(NSString *)groupBy
  2438. {
  2439. [CCUtility setGroupBySettings:groupBy];
  2440. // Clear data-read of DataSource
  2441. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2442. }
  2443. #pragma --------------------------------------------------------------------------------------------
  2444. #pragma mark ==== Menu LOGO ====
  2445. #pragma --------------------------------------------------------------------------------------------
  2446. - (void)menuLogo
  2447. {
  2448. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2449. return;
  2450. // Brand
  2451. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2452. return;
  2453. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutoUploadWithSession:nil] > 0) {
  2454. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2455. return;
  2456. }
  2457. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2458. NSMutableArray *menuArray = [NSMutableArray new];
  2459. for (NSString *account in listAccount) {
  2460. if ([account isEqualToString:app.activeAccount]) continue;
  2461. CCMenuItem *item = [[CCMenuItem alloc] init];
  2462. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2463. item.argument = account;
  2464. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2465. item.target = self;
  2466. item.action = @selector(changeDefaultAccount:);
  2467. [menuArray addObject:item];
  2468. }
  2469. if ([menuArray count] == 0)
  2470. return;
  2471. OptionalConfiguration options;
  2472. Color textColor, backgroundColor;
  2473. textColor.R = 0;
  2474. textColor.G = 0;
  2475. textColor.B = 0;
  2476. backgroundColor.R = 1;
  2477. backgroundColor.G = 1;
  2478. backgroundColor.B = 1;
  2479. NSInteger originY = 60;
  2480. options.arrowSize = 9;
  2481. options.marginXSpacing = 7;
  2482. options.marginYSpacing = 10;
  2483. options.intervalSpacing = 20;
  2484. options.menuCornerRadius = 6.5;
  2485. options.maskToBackground = NO;
  2486. options.shadowOfMenu = YES;
  2487. options.hasSeperatorLine = YES;
  2488. options.seperatorLineHasInsets = YES;
  2489. options.textColor = textColor;
  2490. options.menuBackgroundColor = backgroundColor;
  2491. CGRect rect = self.view.frame;
  2492. rect.origin.y = rect.origin.y + originY;
  2493. rect.size.height = rect.size.height - originY;
  2494. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2495. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2496. }
  2497. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2498. {
  2499. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2500. // STOP, erase all in queue networking
  2501. [app cancelAllOperations];
  2502. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2503. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2504. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2505. if (tableAccount)
  2506. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2507. // go to home sweet home
  2508. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2509. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2510. });
  2511. }
  2512. #pragma --------------------------------------------------------------------------------------------
  2513. #pragma mark ==== ReMenu ====
  2514. #pragma --------------------------------------------------------------------------------------------
  2515. - (void)createReMenuBackgroundView:(REMenu *)menu
  2516. {
  2517. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2518. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2519. [UIView animateWithDuration:0.2 animations:^{
  2520. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2521. if (height < self.tabBarController.tabBar.frame.size.height)
  2522. height = self.tabBarController.tabBar.frame.size.height;
  2523. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2524. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2525. }];
  2526. }
  2527. - (void)createReMainMenu
  2528. {
  2529. NSString *ordinamento;
  2530. NSString *groupBy = _directoryGroupBy;
  2531. __block NSString *nuovoOrdinamento;
  2532. NSString *titoloNuovo, *titoloAttuale;
  2533. BOOL ascendente;
  2534. __block BOOL nuovoAscendente;
  2535. UIImage *image;
  2536. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2537. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2538. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2539. [self tableViewSelect:YES];
  2540. }
  2541. }];
  2542. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2543. ordinamento = _directoryOrder;
  2544. if ([ordinamento isEqualToString:@"fileName"]) {
  2545. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2546. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2547. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2548. nuovoOrdinamento = @"date";
  2549. }
  2550. if ([ordinamento isEqualToString:@"date"]) {
  2551. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2552. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2553. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2554. nuovoOrdinamento = @"fileName";
  2555. }
  2556. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2557. [self orderTable:nuovoOrdinamento];
  2558. }];
  2559. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2560. ascendente = [CCUtility getAscendingSettings];
  2561. if (ascendente) {
  2562. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2563. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2564. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2565. nuovoAscendente = false;
  2566. }
  2567. if (!ascendente) {
  2568. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2569. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2570. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2571. nuovoAscendente = true;
  2572. }
  2573. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2574. [self ascendingTable:nuovoAscendente];
  2575. }];
  2576. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2577. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2578. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2579. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2580. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2581. else [self tableGroupBy:@"alphabetic"];
  2582. }];
  2583. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2584. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2585. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2586. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2587. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2588. else [self tableGroupBy:@"typefile"];
  2589. }];
  2590. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2591. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2592. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2593. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2594. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2595. else [self tableGroupBy:@"date"];
  2596. }];
  2597. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2598. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2599. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2600. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2601. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2602. else [self directoryOnTop:YES];
  2603. }];
  2604. // REMENU --------------------------------------------------------------------------------------------------------------
  2605. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2606. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2607. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2608. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2609. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2610. app.reMainMenu.separatorHeight = 0.5;
  2611. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2612. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2613. app.reMainMenu.textColor = [UIColor blackColor];
  2614. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2615. app.reMainMenu.textShadowColor = nil;
  2616. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2617. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2618. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2619. app.reMainMenu.highlightedSeparatorColor = nil;
  2620. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2621. app.reMainMenu.highlightedTextShadowColor = nil;
  2622. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2623. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2624. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2625. app.reMainMenu.subtitleTextShadowColor = nil;
  2626. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2627. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2628. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2629. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2630. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2631. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2632. app.reMainMenu.borderWidth = 0.3;
  2633. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2634. app.reMainMenu.animationDuration = 0.2;
  2635. app.reMainMenu.closeAnimationDuration = 0.2;
  2636. app.reMainMenu.bounce = NO;
  2637. [app.reMainMenu setClosePreparationBlock:^{
  2638. // Backgroun reMenu (Gesture)
  2639. [_reMenuBackgroundView removeFromSuperview];
  2640. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2641. }];
  2642. }
  2643. - (void)toggleReMainMenu
  2644. {
  2645. if (app.reMainMenu.isOpen) {
  2646. [app.reMainMenu close];
  2647. } else {
  2648. [self createReMainMenu];
  2649. [app.reMainMenu showFromNavigationController:self.navigationController];
  2650. // Backgroun reMenu & (Gesture)
  2651. [self createReMenuBackgroundView:app.reMainMenu];
  2652. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2653. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2654. }
  2655. }
  2656. - (void)createReSelectMenu
  2657. {
  2658. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2659. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2660. [self deleteSelectionFile];
  2661. }];
  2662. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2663. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2664. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2665. }];
  2666. if (app.isCryptoCloudMode) {
  2667. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2668. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2669. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2670. }];
  2671. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2672. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2673. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2674. }];
  2675. }
  2676. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2677. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2678. [self downloadSelectedFilesFolders];
  2679. }];
  2680. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2681. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2682. [self saveSelectedFiles];
  2683. }];
  2684. // REMENU --------------------------------------------------------------------------------------------------------------
  2685. if (app.isCryptoCloudMode) {
  2686. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2687. } else {
  2688. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2689. }
  2690. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2691. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2692. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2693. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2694. app.reSelectMenu.separatorHeight = 0.5;
  2695. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2696. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2697. app.reSelectMenu.textColor = [UIColor blackColor];
  2698. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2699. app.reSelectMenu.textShadowColor = nil;
  2700. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2701. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2702. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2703. app.reSelectMenu.highlightedSeparatorColor = nil;
  2704. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2705. app.reSelectMenu.highlightedTextShadowColor = nil;
  2706. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2707. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2708. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2709. app.reSelectMenu.subtitleTextShadowColor = nil;
  2710. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2711. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2712. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2713. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2714. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2715. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2716. app.reSelectMenu.borderWidth = 0.3;
  2717. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2718. app.reSelectMenu.closeAnimationDuration = 0.2;
  2719. app.reSelectMenu.animationDuration = 0.2;
  2720. app.reSelectMenu.bounce = NO;
  2721. [app.reSelectMenu setClosePreparationBlock:^{
  2722. // Backgroun reMenu (Gesture)
  2723. [_reMenuBackgroundView removeFromSuperview];
  2724. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2725. }];
  2726. }
  2727. - (void)toggleReSelectMenu
  2728. {
  2729. if (app.reSelectMenu.isOpen) {
  2730. [app.reSelectMenu close];
  2731. } else {
  2732. [self createReSelectMenu];
  2733. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2734. // Backgroun reMenu & (Gesture)
  2735. [self createReMenuBackgroundView:app.reSelectMenu];
  2736. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2737. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2738. }
  2739. }
  2740. #pragma --------------------------------------------------------------------------------------------
  2741. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2742. #pragma --------------------------------------------------------------------------------------------
  2743. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2744. {
  2745. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2746. UITableView *tableView = (UITableView*)self.view;
  2747. CGPoint touchPoint = [recognizer locationInView:self.view];
  2748. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2749. if (indexPath)
  2750. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2751. else
  2752. _metadata = nil;
  2753. [self becomeFirstResponder];
  2754. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2755. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2756. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2757. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2758. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2759. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2760. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2761. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2762. if (app.isCryptoCloudMode)
  2763. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2764. else
  2765. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2766. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2767. [menuController setMenuVisible:YES animated:YES];
  2768. }
  2769. }
  2770. - (BOOL)canBecomeFirstResponder
  2771. {
  2772. return YES;
  2773. }
  2774. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2775. {
  2776. // For copy file, copy files, Open in ... :
  2777. //
  2778. // NO Directory
  2779. // NO Error Passcode
  2780. // NO In Session mode (download/upload)
  2781. // NO Template
  2782. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2783. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2784. // NO Cryptated with Title lenght = 0
  2785. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2786. return YES;
  2787. }
  2788. return NO;
  2789. }
  2790. if (@selector(copyFiles:) == action) {
  2791. if (_isSelectedMode) {
  2792. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2793. for (tableMetadata *metadata in selectedMetadatas) {
  2794. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2795. // NO Cryptated with Title lenght = 0
  2796. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2797. return YES;
  2798. }
  2799. }
  2800. }
  2801. return NO;
  2802. }
  2803. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2804. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2805. NSArray *items = [pasteboard items];
  2806. if ([items count] == 1) {
  2807. // Value : (NSData) fileID
  2808. NSDictionary *dic = [items objectAtIndex:0];
  2809. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2810. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2811. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2812. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2813. if (directoryUser) {
  2814. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2815. return YES;
  2816. }
  2817. return NO;
  2818. } else return NO;
  2819. }
  2820. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2821. BOOL isValid = NO;
  2822. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2823. NSArray *items = [pasteboard items];
  2824. if ([items count] <= 1) return NO;
  2825. for (NSDictionary *dic in items) {
  2826. // Value : (NSData) fileID
  2827. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2828. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2829. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2830. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2831. if (directoryUser) {
  2832. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2833. isValid = YES;
  2834. }
  2835. }
  2836. return isValid;
  2837. }
  2838. return NO;
  2839. }
  2840. /************************************ COPY ************************************/
  2841. - (void)copyFile:(id)sender
  2842. {
  2843. // Remove all item
  2844. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2845. pasteboard.items = [[NSArray alloc] init];
  2846. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2847. [self copyFileToPasteboard:_metadata];
  2848. } else {
  2849. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2850. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2851. }
  2852. }
  2853. - (void)copyFiles:(id)sender
  2854. {
  2855. // Remove all item
  2856. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2857. pasteboard.items = [[NSArray alloc] init];
  2858. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2859. for (tableMetadata *metadata in selectedMetadatas) {
  2860. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2861. [self copyFileToPasteboard:metadata];
  2862. } else {
  2863. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2864. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2865. }
  2866. }
  2867. [self tableViewSelect:NO];
  2868. }
  2869. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2870. {
  2871. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2872. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2873. // Value : (NSData) fileID
  2874. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2875. [items addObject:item];
  2876. [pasteboard setItems:items];
  2877. }
  2878. /************************************ OPEN IN ... ************************************/
  2879. - (void)openinFile:(id)sender
  2880. {
  2881. [self openIn:_metadata];
  2882. }
  2883. /************************************ PASTE ************************************/
  2884. - (void)pasteFile:(id)sender
  2885. {
  2886. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2887. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2888. }
  2889. - (void)pasteFileEncrypted:(id)sender
  2890. {
  2891. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2892. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2893. }
  2894. - (void)pasteFiles:(id)sender
  2895. {
  2896. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2897. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2898. }
  2899. - (void)pasteFilesEncrypted:(id)sender
  2900. {
  2901. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2902. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2903. }
  2904. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2905. {
  2906. for (NSDictionary *dic in items) {
  2907. // Value : (NSData) fileID
  2908. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2909. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2910. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2911. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2912. if (!metadata || !account) return;
  2913. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2914. if (directoryUser) {
  2915. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2916. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2917. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2918. }
  2919. }
  2920. }
  2921. }
  2922. #pragma --------------------------------------------------------------------------------------------
  2923. #pragma mark ===== Lock Passcode =====
  2924. #pragma --------------------------------------------------------------------------------------------
  2925. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2926. {
  2927. return _failedAttempts;
  2928. }
  2929. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2930. {
  2931. return _lockUntilDate;
  2932. }
  2933. - (void)passcodeViewCloseButtonPressed:(id)sender
  2934. {
  2935. [self dismissViewControllerAnimated:YES completion:nil];
  2936. }
  2937. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2938. {
  2939. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2940. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2941. _lockUntilDate = nil;
  2942. _failedAttempts = 0;
  2943. aResultHandler(YES);
  2944. } else aResultHandler(NO);
  2945. } else aResultHandler(YES);
  2946. }
  2947. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2948. {
  2949. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2950. switch (aViewController.type) {
  2951. case BKPasscodeViewControllerCheckPasscodeType: {
  2952. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2953. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2954. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2955. // scriviamo il passcode
  2956. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2957. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2958. } else {
  2959. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2960. [alertView show];
  2961. }
  2962. }
  2963. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2964. // possiamo procedere alla prossima directory
  2965. [self performSegueDirectoryWithControlPasscode:false];
  2966. // avviamo la sessione Passcode Lock con now
  2967. app.sessionePasscodeLock = [NSDate date];
  2968. }
  2969. // disattivazione lock cartella
  2970. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2971. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2972. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2973. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2974. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2975. }
  2976. [self tableViewReload];
  2977. }
  2978. }
  2979. break;
  2980. default:
  2981. break;
  2982. }
  2983. }
  2984. - (void)comandoLockPassword
  2985. {
  2986. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2987. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2988. // se non è abilitato il Lock Passcode esci
  2989. if ([[CCUtility getBlockCode] length] == 0) {
  2990. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2991. [alertView show];
  2992. return;
  2993. }
  2994. // se è richiesta la disattivazione si chiede la password
  2995. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2996. if (directory.lock) {
  2997. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2998. viewController.delegate = self;
  2999. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  3000. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3001. viewController.inputViewTitlePassword = YES;
  3002. if ([CCUtility getSimplyBlockCode]) {
  3003. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3004. viewController.passcodeInputView.maximumLength = 6;
  3005. } else {
  3006. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3007. viewController.passcodeInputView.maximumLength = 64;
  3008. }
  3009. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3010. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3011. viewController.touchIDManager = touchIDManager;
  3012. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  3013. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3014. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3015. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3016. [self presentViewController:navigationController animated:YES completion:nil];
  3017. return;
  3018. }
  3019. // ---------------- ACTIVATE PASSWORD
  3020. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  3021. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3022. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3023. } else {
  3024. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3025. }
  3026. }
  3027. #pragma mark -
  3028. #pragma --------------------------------------------------------------------------------------------
  3029. #pragma mark ===== Swipe Tablet -> menu =====
  3030. #pragma --------------------------------------------------------------------------------------------
  3031. // more
  3032. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  3033. return NSLocalizedString(@"_more_", nil);
  3034. }
  3035. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  3036. {
  3037. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3038. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3039. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  3040. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3041. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3042. if (_metadata.favorite) {
  3043. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3044. } else {
  3045. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3046. }
  3047. if (_metadata.directory) {
  3048. // calcolo lockServerUrl
  3049. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3050. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3051. if (directory.lock)
  3052. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3053. else
  3054. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3055. }
  3056. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  3057. /******************************************* AHKActionSheet *******************************************/
  3058. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3059. actionSheet.animationDuration = 0.2;
  3060. actionSheet.blurRadius = 0.0f;
  3061. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3062. actionSheet.buttonHeight = 50.0;
  3063. actionSheet.cancelButtonHeight = 50.0f;
  3064. actionSheet.separatorHeight = 5.0f;
  3065. actionSheet.automaticallyTintButtonImages = @(NO);
  3066. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3067. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3068. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3069. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3070. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3071. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3072. /******************************************* DIRECTORY *******************************************/
  3073. if (_metadata.directory) {
  3074. BOOL lockDirectory = NO;
  3075. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3076. // Directory bloccata ?
  3077. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3078. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3079. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3080. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3081. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3082. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3083. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3084. height: 50.0
  3085. type: AHKActionSheetButtonTypeDisabled
  3086. handler: nil
  3087. ];
  3088. if (!lockDirectory && !_metadata.cryptated) {
  3089. [actionSheet addButtonWithTitle:titleFavorite
  3090. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3091. backgroundColor:[UIColor whiteColor]
  3092. height: 50.0
  3093. type:AHKActionSheetButtonTypeDefault
  3094. handler:^(AHKActionSheet *as) {
  3095. // close swipe
  3096. [self setEditing:NO animated:YES];
  3097. if (_metadata.favorite)
  3098. [self removeFavorite:_metadata];
  3099. else
  3100. [self addFavorite:_metadata];
  3101. }];
  3102. }
  3103. if (_metadata.cryptated == NO && !lockDirectory) {
  3104. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3105. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3106. backgroundColor:[UIColor whiteColor]
  3107. height: 50.0
  3108. type:AHKActionSheetButtonTypeDefault
  3109. handler:^(AHKActionSheet *as) {
  3110. // close swipe
  3111. [self setEditing:NO animated:YES];
  3112. [self openWindowShare:_metadata];
  3113. }];
  3114. }
  3115. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3116. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3117. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3118. backgroundColor:[UIColor whiteColor]
  3119. height: 50.0
  3120. type:AHKActionSheetButtonTypeDefault
  3121. handler:^(AHKActionSheet *as) {
  3122. // close swipe
  3123. [self setEditing:NO animated:YES];
  3124. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3125. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3126. textField.text = _metadata.fileNamePrint;
  3127. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  3128. //textField.delegate = self;
  3129. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3130. }];
  3131. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3132. NSLog(@"Cancel action");
  3133. }];
  3134. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3135. UITextField *fileName = alertController.textFields.firstObject;
  3136. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3137. }];
  3138. okAction.enabled = NO;
  3139. [alertController addAction:cancelAction];
  3140. [alertController addAction:okAction];
  3141. [self presentViewController:alertController animated:YES completion:nil];
  3142. }];
  3143. }
  3144. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3145. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3146. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3147. backgroundColor:[UIColor whiteColor]
  3148. height: 50.0
  3149. type:AHKActionSheetButtonTypeDefault
  3150. handler:^(AHKActionSheet *as) {
  3151. // close swipe
  3152. [self setEditing:NO animated:YES];
  3153. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3154. }];
  3155. }
  3156. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && _metadata.cryptated == NO) {
  3157. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3158. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3159. backgroundColor:[UIColor whiteColor]
  3160. height: 50.0
  3161. type:AHKActionSheetButtonTypeDefault
  3162. handler:^(AHKActionSheet *as) {
  3163. // close swipe
  3164. [self setEditing:NO animated:YES];
  3165. // Settings new folder Automatatic upload
  3166. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3167. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3168. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3169. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3170. if (app.activeAccount.length > 0 && app.activePhotos)
  3171. [app.activePhotos reloadDatasourceForced];
  3172. [self readFolderWithForced:YES serverUrl:serverUrl];
  3173. NSLog(@"[LOG] Update Folder Photo");
  3174. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3175. if ([autoUploadPath length] > 0)
  3176. [[CCSynchronize sharedSynchronize] synchronizedFolder:autoUploadPath selector:selectorReadFolder];
  3177. }];
  3178. }
  3179. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3180. [actionSheet addButtonWithTitle:titoloLock
  3181. image:[UIImage imageNamed:@"actionSheetLock"]
  3182. backgroundColor:[UIColor whiteColor]
  3183. height: 50.0
  3184. type:AHKActionSheetButtonTypeEncrypted
  3185. handler:^(AHKActionSheet *as) {
  3186. // close swipe
  3187. [self setEditing:NO animated:YES];
  3188. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3189. }];
  3190. }
  3191. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3192. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3193. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3194. backgroundColor:[UIColor whiteColor]
  3195. height: 50.0
  3196. type:AHKActionSheetButtonTypeEncrypted
  3197. handler:^(AHKActionSheet *as) {
  3198. // close swipe
  3199. [self setEditing:NO animated:YES];
  3200. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3201. }];
  3202. }
  3203. [actionSheet show];
  3204. }
  3205. /******************************************* FILE *******************************************/
  3206. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3207. UIImage *iconHeader;
  3208. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3209. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3210. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3211. else
  3212. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3213. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3214. image: iconHeader
  3215. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3216. height: 50.0
  3217. type: AHKActionSheetButtonTypeDisabled
  3218. handler: nil
  3219. ];
  3220. if (!_metadata.cryptated) {
  3221. [actionSheet addButtonWithTitle:titleFavorite
  3222. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3223. backgroundColor:[UIColor whiteColor]
  3224. height: 50.0
  3225. type:AHKActionSheetButtonTypeDefault
  3226. handler:^(AHKActionSheet *as) {
  3227. // close swipe
  3228. [self setEditing:NO animated:YES];
  3229. if (_metadata.favorite)
  3230. [self removeFavorite:_metadata];
  3231. else
  3232. [self addFavorite:_metadata];
  3233. }];
  3234. }
  3235. if (_metadata.cryptated == NO) {
  3236. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3237. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3238. backgroundColor:[UIColor whiteColor]
  3239. height: 50.0
  3240. type:AHKActionSheetButtonTypeDefault
  3241. handler:^(AHKActionSheet *as) {
  3242. // close swipe
  3243. [self setEditing:NO animated:YES];
  3244. [self openWindowShare:_metadata];
  3245. }];
  3246. }
  3247. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3248. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3249. backgroundColor:[UIColor whiteColor]
  3250. height: 50.0
  3251. type:AHKActionSheetButtonTypeDefault
  3252. handler:^(AHKActionSheet *as) {
  3253. // close swipe
  3254. [self setEditing:NO animated:YES];
  3255. [self performSelector:@selector(openIn:) withObject:_metadata];
  3256. }];
  3257. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3258. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3259. backgroundColor:[UIColor whiteColor]
  3260. height: 50.0
  3261. type:AHKActionSheetButtonTypeDefault
  3262. handler:^(AHKActionSheet *as) {
  3263. // close swipe
  3264. [self setEditing:NO animated:YES];
  3265. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3266. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3267. //textField.placeholder = _metadata.fileNamePrint;
  3268. textField.text = _metadata.fileNamePrint;
  3269. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3270. }];
  3271. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3272. NSLog(@"Cancel action");
  3273. }];
  3274. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3275. UITextField *fileName = alertController.textFields.firstObject;
  3276. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3277. }];
  3278. okAction.enabled = NO;
  3279. [alertController addAction:cancelAction];
  3280. [alertController addAction:okAction];
  3281. [self presentViewController:alertController animated:YES completion:nil];
  3282. }];
  3283. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3284. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3285. backgroundColor:[UIColor whiteColor]
  3286. height: 50.0
  3287. type:AHKActionSheetButtonTypeDefault
  3288. handler:^(AHKActionSheet *as) {
  3289. // close swipe
  3290. [self setEditing:NO animated:YES];
  3291. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3292. }];
  3293. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3294. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3295. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3296. backgroundColor:[UIColor whiteColor]
  3297. height: 50.0
  3298. type:AHKActionSheetButtonTypeDefault
  3299. handler:^(AHKActionSheet *as) {
  3300. // close swipe
  3301. [self setEditing:NO animated:YES];
  3302. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3303. }];
  3304. }
  3305. if (app.isCryptoCloudMode) {
  3306. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3307. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3308. backgroundColor:[UIColor whiteColor]
  3309. height: 50.0
  3310. type:AHKActionSheetButtonTypeEncrypted
  3311. handler:^(AHKActionSheet *as) {
  3312. // close swipe
  3313. [self setEditing:NO animated:YES];
  3314. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3315. }];
  3316. }
  3317. [actionSheet show];
  3318. }
  3319. /******************************************* TEMPLATE *******************************************/
  3320. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3321. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3322. image: [UIImage imageNamed:_metadata.iconName]
  3323. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3324. height: 50.0
  3325. type: AHKActionSheetButtonTypeDisabled
  3326. handler: nil
  3327. ];
  3328. if ([_metadata.model isEqualToString:@"note"]) {
  3329. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3330. image:[UIImage imageNamed:@"actionSheetRename"]
  3331. backgroundColor:[UIColor whiteColor]
  3332. height: 50.0
  3333. type:AHKActionSheetButtonTypeDefault
  3334. handler:^(AHKActionSheet *as) {
  3335. // close swipe
  3336. [self setEditing:NO animated:YES];
  3337. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3338. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3339. textField.placeholder = _metadata.fileNamePrint;
  3340. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3341. }];
  3342. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3343. NSLog(@"Cancel action");
  3344. }];
  3345. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3346. UITextField *fileName = alertController.textFields.firstObject;
  3347. [self performSelectorOnMainThread:@selector(renameNote:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3348. }];
  3349. okAction.enabled = NO;
  3350. [alertController addAction:cancelAction];
  3351. [alertController addAction:okAction];
  3352. [self presentViewController:alertController animated:YES completion:nil];
  3353. }];
  3354. }
  3355. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3356. image:[UIImage imageNamed:@"actionSheetMove"]
  3357. backgroundColor:[UIColor whiteColor]
  3358. height: 50.0
  3359. type:AHKActionSheetButtonTypeDefault
  3360. handler:^(AHKActionSheet *as) {
  3361. // close swipe
  3362. [self setEditing:NO animated:YES];
  3363. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3364. }];
  3365. [actionSheet show];
  3366. }
  3367. }
  3368. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3369. {
  3370. return NSLocalizedString(@"_delete_", nil);
  3371. }
  3372. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3373. {
  3374. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3375. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3376. return NO;
  3377. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3378. else return YES;
  3379. }
  3380. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3381. {
  3382. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3383. if (_metadata.errorPasscode || (_metadata.cryptated && [_metadata.title length] == 0) || _metadata.sessionTaskIdentifier >= 0 || _metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3384. else return UITableViewCellEditingStyleDelete;
  3385. }
  3386. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3387. {
  3388. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3389. BOOL lockDirectory = NO;
  3390. // Directory locked ?
  3391. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3392. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3393. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil)
  3394. lockDirectory = YES;
  3395. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3396. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3397. return;
  3398. }
  3399. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3400. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3401. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3402. style:UIAlertActionStyleDestructive
  3403. handler:^(UIAlertAction *action) {
  3404. [self performSelector:@selector(deleteFile) withObject:nil];
  3405. }]];
  3406. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3407. style:UIAlertActionStyleCancel
  3408. handler:^(UIAlertAction *action) {
  3409. [alertController dismissViewControllerAnimated:YES completion:nil];
  3410. }]];
  3411. alertController.popoverPresentationController.sourceView = self.view;
  3412. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3413. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3414. [alertController.view layoutIfNeeded];
  3415. [self presentViewController:alertController animated:YES completion:nil];
  3416. }
  3417. }
  3418. #pragma --------------------------------------------------------------------------------------------
  3419. #pragma mark - ==== Datasource ====
  3420. #pragma --------------------------------------------------------------------------------------------
  3421. - (void)clearDateReadDataSource:(NSNotification *)notification
  3422. {
  3423. _dateReadDataSource = Nil;
  3424. [self reloadDatasource];
  3425. }
  3426. - (void)reloadDatasource
  3427. {
  3428. [self reloadDatasource:_serverUrl selector:nil];
  3429. }
  3430. - (void)reloadDatasource:(NSString *)serverUrl selector:(NSString *)selector
  3431. {
  3432. // test
  3433. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3434. return;
  3435. // Search Mode
  3436. if(_isSearchMode) {
  3437. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3438. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3439. } else {
  3440. [self readFolderWithForced:NO serverUrl:serverUrl];
  3441. }
  3442. [self tableViewReload];
  3443. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3444. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3445. _noFilesSearchDescription = @"";
  3446. }
  3447. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3448. _noFilesSearchTitle = @"";
  3449. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3450. }
  3451. [self.tableView reloadEmptyDataSet];
  3452. return;
  3453. }
  3454. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3455. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3456. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3457. if (main) {
  3458. [main reloadDatasource];
  3459. } else {
  3460. [self tableViewReload];
  3461. [app.activeTransfers reloadDatasource];
  3462. }
  3463. return;
  3464. }
  3465. [app.activeTransfers reloadDatasource];
  3466. // Settaggio variabili per le ottimizzazioni
  3467. _directoryGroupBy = [CCUtility getGroupBySettings];
  3468. _directoryOrder = [CCUtility getOrderSettings];
  3469. // Controllo data lettura Data Source
  3470. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl == %@", serverUrl]];
  3471. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3472. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3473. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3474. _dateReadDataSource = [NSDate date];
  3475. // Data Source
  3476. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3477. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3478. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3479. } else {
  3480. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3481. }
  3482. [self tableViewReload];
  3483. }
  3484. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3485. {
  3486. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3487. if (selectedRows.count > 0) {
  3488. for (NSIndexPath *selectionIndex in selectedRows) {
  3489. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3490. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3491. [metadatas addObject:metadata];
  3492. }
  3493. }
  3494. return metadatas;
  3495. }
  3496. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3497. {
  3498. NSInteger section = indexPath.section + 1;
  3499. NSInteger row = indexPath.row + 1;
  3500. NSInteger totSections =[_sectionDataSource.sections count] ;
  3501. if ((totSections < section) || (section > totSections)) {
  3502. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3503. return nil;
  3504. }
  3505. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3506. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3507. if (fileIDs) {
  3508. NSInteger totRows =[fileIDs count] ;
  3509. if ((totRows < row) || (row > totRows)) {
  3510. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3511. return nil;
  3512. }
  3513. } else {
  3514. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3515. return nil;
  3516. }
  3517. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3518. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3519. return metadata;
  3520. }
  3521. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3522. {
  3523. NSInteger totSections =[_sectionDataSource.sections count] ;
  3524. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3525. #if DEBUG
  3526. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3527. [alertView show];
  3528. #endif
  3529. return nil;
  3530. }
  3531. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3532. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3533. }
  3534. #pragma --------------------------------------------------------------------------------------------
  3535. #pragma mark - ==== Table ====
  3536. #pragma --------------------------------------------------------------------------------------------
  3537. - (void)tableViewSelect:(BOOL)edit
  3538. {
  3539. // chiudiamo eventuali swipe aperti
  3540. if (edit) [self.tableView setEditing:NO animated:NO];
  3541. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3542. [self.tableView setEditing:edit animated:YES];
  3543. _isSelectedMode = edit;
  3544. if (edit)
  3545. [self setUINavigationBarSelected];
  3546. else
  3547. [self setUINavigationBarDefault];
  3548. [self setTitle];
  3549. }
  3550. - (void)tableViewReload
  3551. {
  3552. // ricordiamoci le row selezionate
  3553. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3554. [self.tableView reloadData];
  3555. for (NSIndexPath *path in indexPaths)
  3556. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3557. [self setTableViewFooter];
  3558. if (self.tableView.editing)
  3559. [self setTitle];
  3560. }
  3561. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3562. {
  3563. return 60;
  3564. }
  3565. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3566. {
  3567. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3568. }
  3569. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3570. {
  3571. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3572. }
  3573. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3574. {
  3575. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3576. NSString *sectionTitle = [sections objectAtIndex:section];
  3577. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3578. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3579. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3580. return 20.f;
  3581. }
  3582. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3583. {
  3584. float shift;
  3585. UIVisualEffectView *visualEffectView;
  3586. // Titolo
  3587. NSString *titleSection;
  3588. // Controllo
  3589. if ([_sectionDataSource.sections count] == 0)
  3590. return nil;
  3591. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3592. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3593. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3594. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3595. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3596. else titleSection = NSLocalizedString(titleSection,nil);
  3597. // Formato titolo
  3598. NSString *currentDevice = [CCUtility currentDevice];
  3599. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3600. visualEffectView = [[UIVisualEffectView alloc] init];
  3601. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3602. } else {
  3603. UIVisualEffect *blurEffect;
  3604. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3605. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3606. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3607. }
  3608. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3609. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3610. else shift = - 20;
  3611. } else shift = - 10;
  3612. // Title
  3613. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3614. titleLabel.backgroundColor = [UIColor clearColor];
  3615. titleLabel.textColor = [UIColor blackColor];
  3616. titleLabel.font = [UIFont systemFontOfSize:12];
  3617. titleLabel.textAlignment = NSTextAlignmentLeft;
  3618. titleLabel.text = titleSection;
  3619. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3620. [visualEffectView addSubview:titleLabel];
  3621. // Elements
  3622. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3623. elementLabel.backgroundColor = [UIColor clearColor];
  3624. elementLabel.textColor = [UIColor blackColor];;
  3625. elementLabel.font = [UIFont systemFontOfSize:12];
  3626. elementLabel.textAlignment = NSTextAlignmentRight;
  3627. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3628. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3629. NSUInteger rowsCount = [metadatas count];
  3630. if (rowsCount == 0) return nil;
  3631. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3632. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3633. [visualEffectView addSubview:elementLabel];
  3634. return visualEffectView;
  3635. }
  3636. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3637. {
  3638. return [_sectionDataSource.sections indexOfObject:title];
  3639. }
  3640. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3641. {
  3642. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3643. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3644. else
  3645. return nil;
  3646. }
  3647. /*
  3648. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3649. {
  3650. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3651. }
  3652. }
  3653. */
  3654. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3655. {
  3656. NSString *typeCell;
  3657. NSString *dataFile;
  3658. NSString *lunghezzaFile;
  3659. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3660. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3661. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3662. }
  3663. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3664. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3665. else typeCell = @"CellMainTransfer";
  3666. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3667. // separator
  3668. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3669. // change color selection
  3670. UIView *selectionColor = [[UIView alloc] init];
  3671. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3672. cell.selectedBackgroundView = selectionColor;
  3673. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3674. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3675. // ----------------------------------------------------------------------------------------------------------
  3676. // DEFAULT
  3677. // ----------------------------------------------------------------------------------------------------------
  3678. cell.file.image = nil;
  3679. cell.status.image = nil;
  3680. cell.favorite.image = nil;
  3681. cell.shared.image = nil;
  3682. cell.local.image = nil;
  3683. cell.labelTitle.enabled = YES;
  3684. cell.labelTitle.text = @"";
  3685. cell.labelInfoFile.enabled = YES;
  3686. cell.labelInfoFile.text = @"";
  3687. cell.progressView.progress = 0.0;
  3688. cell.progressView.hidden = YES;
  3689. cell.cancelTaskButton.hidden = YES;
  3690. cell.reloadTaskButton.hidden = YES;
  3691. cell.stopTaskButton.hidden = YES;
  3692. // Encrypted color
  3693. if (metadata.cryptated) {
  3694. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3695. } else {
  3696. cell.labelTitle.textColor = [UIColor blackColor];
  3697. }
  3698. // ----------------------------------------------------------------------------------------------------------
  3699. // File Name & Folder
  3700. // ----------------------------------------------------------------------------------------------------------
  3701. // nome del file
  3702. cell.labelTitle.text = metadata.fileNamePrint;
  3703. // è una directory
  3704. if (metadata.directory) {
  3705. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3706. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3707. lunghezzaFile = @" ";
  3708. // ----------------------------------------------------------------------------------------------------------
  3709. // Favorite Folder
  3710. // ----------------------------------------------------------------------------------------------------------
  3711. if (metadata.favorite) {
  3712. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3713. }
  3714. } else {
  3715. // File
  3716. dataFile = [CCUtility dateDiff:metadata.date];
  3717. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3718. // Plist ancora da scaricare
  3719. if (metadata.cryptated && [metadata.title length] == 0) {
  3720. dataFile = @" ";
  3721. lunghezzaFile = @" ";
  3722. }
  3723. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3724. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3725. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3726. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3727. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3728. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3729. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3730. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3731. cell.local.image = [UIImage imageNamed:@"local"];
  3732. else
  3733. cell.local.image = nil;
  3734. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3735. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3736. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3737. }
  3738. // Plist ancora da scaricare
  3739. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3740. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3741. cell.accessoryType = UITableViewCellAccessoryNone;
  3742. }
  3743. // ----------------------------------------------------------------------------------------------------------
  3744. // File Image View
  3745. // ----------------------------------------------------------------------------------------------------------
  3746. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3747. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3748. cell.file.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3749. if (cell.file.image == nil) {
  3750. NSString *fileID = metadata.fileID;
  3751. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3752. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3753. [app.icoImagesCache setObject:image forKey:fileID];
  3754. dispatch_async(dispatch_get_main_queue(), ^{
  3755. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3756. if (cell)
  3757. cell.file.image = image;
  3758. });
  3759. });
  3760. }
  3761. } else {
  3762. if (metadata.directory)
  3763. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3764. else
  3765. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3766. if (metadata.thumbnailExists)
  3767. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3768. }
  3769. // ----------------------------------------------------------------------------------------------------------
  3770. // Image Status cyptated & Lock Passcode
  3771. // ----------------------------------------------------------------------------------------------------------
  3772. // File Cyptated
  3773. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3774. cell.status.image = [UIImage imageNamed:@"lock"];
  3775. }
  3776. // Directory con passcode lock attivato
  3777. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3778. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3779. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3780. cell.status.image = [UIImage imageNamed:@"passcode"];
  3781. // ----------------------------------------------------------------------------------------------------------
  3782. // Favorite
  3783. // ----------------------------------------------------------------------------------------------------------
  3784. if (metadata.favorite) {
  3785. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3786. }
  3787. // ----------------------------------------------------------------------------------------------------------
  3788. // Share
  3789. // ----------------------------------------------------------------------------------------------------------
  3790. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3791. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3792. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3793. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3794. // Aggiungiamo il Tap per le shared
  3795. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3796. if (isShare) {
  3797. if (metadata.directory) {
  3798. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3799. cell.shared.userInteractionEnabled = NO;
  3800. } else {
  3801. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3802. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3803. [tap setNumberOfTapsRequired:1];
  3804. cell.shared.userInteractionEnabled = YES;
  3805. [cell.shared addGestureRecognizer:tap];
  3806. }
  3807. }
  3808. if (isMounted) {
  3809. if (metadata.directory) {
  3810. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3811. cell.shared.userInteractionEnabled = NO;
  3812. } else {
  3813. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3814. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3815. [tap setNumberOfTapsRequired:1];
  3816. cell.shared.userInteractionEnabled = YES;
  3817. [cell.shared addGestureRecognizer:tap];
  3818. }
  3819. }
  3820. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3821. if (metadata.directory) {
  3822. if ([shareLink length] > 0)
  3823. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3824. if ([shareUserAndGroup length] > 0)
  3825. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3826. cell.shared.userInteractionEnabled = NO;
  3827. } else {
  3828. if ([shareLink length] > 0)
  3829. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3830. if ([shareUserAndGroup length] > 0)
  3831. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3832. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3833. [tap setNumberOfTapsRequired:1];
  3834. cell.shared.userInteractionEnabled = YES;
  3835. [cell.shared addGestureRecognizer:tap];
  3836. }
  3837. }
  3838. } else {
  3839. cell.shared.userInteractionEnabled = NO;
  3840. }
  3841. // ----------------------------------------------------------------------------------------------------------
  3842. // downloadFile
  3843. // ----------------------------------------------------------------------------------------------------------
  3844. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3845. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3846. else cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3847. // sessionTaskIdentifier : RELOAD + STOP
  3848. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3849. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3850. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3851. cell.cancelTaskButton.hidden = NO;
  3852. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3853. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3854. cell.reloadTaskButton.hidden = NO;
  3855. }
  3856. // sessionTaskIdentifierPlist : RELOAD
  3857. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3858. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3859. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3860. cell.reloadTaskButton.hidden = NO;
  3861. }
  3862. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3863. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3864. if (progress > 0) {
  3865. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3866. else cell.progressView.progressTintColor = [UIColor blackColor];
  3867. cell.progressView.progress = progress;
  3868. cell.progressView.hidden = NO;
  3869. }
  3870. // ----------------------------------------------------------------------------------------------------------
  3871. // downloadFile Error
  3872. // ----------------------------------------------------------------------------------------------------------
  3873. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3874. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3875. if ([metadata.sessionError length] == 0)
  3876. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3877. else
  3878. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3879. }
  3880. }
  3881. // ----------------------------------------------------------------------------------------------------------
  3882. // uploadFile
  3883. // ----------------------------------------------------------------------------------------------------------
  3884. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3885. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3886. else cell.status.image = [UIImage imageNamed:@"statusupload"];
  3887. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3888. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3889. cell.cancelTaskButton.hidden = NO;
  3890. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3891. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3892. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3893. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusstopcrypto"];
  3894. else cell.status.image = [UIImage imageNamed:@"statusstop"];
  3895. cell.reloadTaskButton.hidden = NO;
  3896. cell.stopTaskButton.hidden = YES;
  3897. } else {
  3898. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3899. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3900. cell.stopTaskButton.hidden = NO;
  3901. cell.reloadTaskButton.hidden = YES;
  3902. }
  3903. // se non c'è una preview in bianconero metti l'immagine di default
  3904. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3905. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3906. cell.labelTitle.enabled = NO;
  3907. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3908. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3909. if (progress > 0) {
  3910. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3911. else cell.progressView.progressTintColor = [UIColor blackColor];
  3912. cell.progressView.progress = progress;
  3913. cell.progressView.hidden = NO;
  3914. }
  3915. // ----------------------------------------------------------------------------------------------------------
  3916. // uploadFileError
  3917. // ----------------------------------------------------------------------------------------------------------
  3918. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3919. cell.labelTitle.enabled = NO;
  3920. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3921. if ([metadata.sessionError length] == 0)
  3922. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3923. else
  3924. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3925. }
  3926. }
  3927. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3928. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3929. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3930. return cell;
  3931. }
  3932. - (void)setTableViewFooter
  3933. {
  3934. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3935. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3936. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3937. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3938. UIFont *appFont = [UIFont systemFontOfSize:12];
  3939. footerLabel.font = appFont;
  3940. footerLabel.textColor = [UIColor grayColor];
  3941. footerLabel.backgroundColor = [UIColor clearColor];
  3942. footerLabel.textAlignment = NSTextAlignmentCenter;
  3943. NSString *folders;
  3944. NSString *files;
  3945. NSString *footerText;
  3946. if (_sectionDataSource.directories > 1) {
  3947. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3948. } else if (_sectionDataSource.directories == 1){
  3949. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3950. } else {
  3951. folders = @"";
  3952. }
  3953. if (_sectionDataSource.files > 1) {
  3954. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3955. } else if (_sectionDataSource.files == 1){
  3956. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3957. } else {
  3958. files = @"";
  3959. }
  3960. if ([folders isEqualToString:@""]) {
  3961. footerText = files;
  3962. } else if ([files isEqualToString:@""]) {
  3963. footerText = folders;
  3964. } else {
  3965. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3966. }
  3967. footerLabel.text = footerText;
  3968. [footerView addSubview:footerLabel];
  3969. [self.tableView setTableFooterView:footerView];
  3970. }
  3971. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3972. {
  3973. NSString *textMessage;
  3974. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3975. // settiamo il record file.
  3976. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3977. // se non può essere selezionata deseleziona
  3978. if ([cell isEditing] == NO)
  3979. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3980. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3981. if (self.tableView.editing) {
  3982. [self setTitle];
  3983. return;
  3984. }
  3985. // test crash
  3986. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3987. if (indexPath.row >= [metadatas count]) return;
  3988. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3989. // se è in corso una sessione
  3990. if ([_metadata.session length] > 0) return;
  3991. if (_metadata.errorPasscode) {
  3992. // se UUID è nil lo sta ancora caricando quindi esci
  3993. if (!_metadata.uuid) return;
  3994. // esiste un hint ??
  3995. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3996. // qui !! la richiesta della nuova passcode
  3997. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3998. // stesso UUID ... la password è stata modificata !!!!!!
  3999. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  4000. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  4001. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  4002. [alertView show];
  4003. } else {
  4004. // UUID diverso.
  4005. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  4006. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  4007. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  4008. [alertView show];
  4009. }
  4010. // chiediamo la passcode e ricarichiamo tutto.
  4011. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4012. viewController.delegate = self;
  4013. viewController.fromType = CCBKPasscodeFromPasscode;
  4014. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4015. viewController.passcodeInputView.maximumLength = 64;
  4016. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4017. viewController.inputViewTitlePassword = NO;
  4018. viewController.title = [NCBrandOptions sharedInstance].brand;
  4019. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4020. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4021. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4022. [self presentViewController:navigationController animated:YES completion:nil];
  4023. }
  4024. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  4025. if (_metadata.cryptated && [_metadata.title length] == 0) {
  4026. NSString* selector;
  4027. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  4028. else selector = selectorLoadPlist;
  4029. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4030. return;
  4031. }
  4032. // se il plist è caricato ed è un modello aprilo
  4033. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  4034. // file
  4035. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  4036. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  4037. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  4038. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  4039. } else {
  4040. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4041. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  4042. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  4043. }
  4044. }
  4045. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  4046. }
  4047. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  4048. {
  4049. [self setTitle];
  4050. }
  4051. #pragma --------------------------------------------------------------------------------------------
  4052. #pragma mark ===== Navigation ====
  4053. #pragma --------------------------------------------------------------------------------------------
  4054. - (BOOL)shouldPerformSegue
  4055. {
  4056. // if background return
  4057. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4058. if (self.view.window == NO)
  4059. return NO;
  4060. // Collapsed ma siamo già in detail esci
  4061. if (self.splitViewController.isCollapsed)
  4062. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4063. // Video in esecuzione esci
  4064. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4065. return YES;
  4066. }
  4067. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4068. {
  4069. id viewController = segue.destinationViewController;
  4070. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4071. tableMetadata *metadata;
  4072. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4073. UINavigationController *nav = viewController;
  4074. _detailViewController = (CCDetail *)nav.topViewController;
  4075. } else {
  4076. _detailViewController = segue.destinationViewController;
  4077. }
  4078. if ([sender isKindOfClass:[tableMetadata class]]) {
  4079. metadata = sender;
  4080. [allRecordsDataSourceImagesVideos addObject:sender];
  4081. } else {
  4082. metadata = _metadata;
  4083. for (NSString *fileID in _sectionDataSource.allEtag) {
  4084. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4085. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4086. [allRecordsDataSourceImagesVideos addObject:metadata];
  4087. }
  4088. }
  4089. _detailViewController.metadataDetail = metadata;
  4090. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4091. _detailViewController.dateFilterQuery = nil;
  4092. [_detailViewController setTitle:metadata.fileNamePrint];
  4093. }
  4094. // can i go to next viewcontroller
  4095. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4096. {
  4097. NSString *nomeDir;
  4098. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4099. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4100. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4101. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  4102. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4103. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4104. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4105. viewController.delegate = self;
  4106. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4107. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4108. viewController.inputViewTitlePassword = YES;
  4109. if ([CCUtility getSimplyBlockCode]) {
  4110. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4111. viewController.passcodeInputView.maximumLength = 6;
  4112. } else {
  4113. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4114. viewController.passcodeInputView.maximumLength = 64;
  4115. }
  4116. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4117. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4118. viewController.touchIDManager = touchIDManager;
  4119. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4120. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4121. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4122. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4123. [self presentViewController:navController animated:YES completion:nil];
  4124. return;
  4125. }
  4126. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4127. else nomeDir = _metadata.fileName;
  4128. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4129. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4130. if (viewController.isViewLoaded == false || viewController == nil) {
  4131. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4132. viewController.isFolderEncrypted = _metadata.cryptated;
  4133. viewController.serverUrl = serverUrlPush;
  4134. viewController.titleMain = _metadata.fileNamePrint;
  4135. viewController.textBackButton = _titleMain;
  4136. // save self
  4137. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4138. }
  4139. // OFF SearchBar
  4140. [viewController cancelSearchBar];
  4141. [self.navigationController pushViewController:viewController animated:YES];
  4142. }
  4143. }
  4144. @end