CCMain.m 249 KB

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