CCMain.m 251 KB

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